<?php
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once '../../../dripend/includes/db.php';

$message = '';

// ==============================================================================
// 1. FETCH SYSTEM DICTIONARIES (STRICTLY FILTERED)
// ==============================================================================
// Fetch all physical locations
$locations = $conn->query("SELECT id, location_name, location_type FROM inventory_locations WHERE is_active = 1 ORDER BY location_name ASC")->fetch_all(MYSQLI_ASSOC);

// THE CENTRAL POOL: Fetch ONLY physical items (Drugs & Consumables). NO PROCEDURES.
$catalog_items = $conn->query("
    SELECT sc.id, sc.service_name, sc.unit_of_pricing, ic.category_name 
    FROM service_catalog sc
    JOIN item_categories ic ON sc.category_id = ic.id
    WHERE sc.is_active = 1 AND sc.service_type = 'Drug' 
    ORDER BY sc.service_name ASC
")->fetch_all(MYSQLI_ASSOC);

// ==============================================================================
// 2. FORM PROCESSING (ALLOCATE TO STORE)
// ==============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $location_id = (int)$_POST['location_id'];
    $service_id = (int)$_POST['service_id'];
    $quantity = (int)$_POST['quantity'];

    if ($location_id > 0 && $service_id > 0 && $quantity >= 0) {
        $conn->begin_transaction();
        try {
            // Check if this specific store already has a bin/shelf for this exact item
            $check_stmt = $conn->prepare("SELECT id, quantity FROM inventory_stock WHERE service_id = ? AND location_id = ?");
            $check_stmt->bind_param("ii", $service_id, $location_id);
            $check_stmt->execute();
            $result = $check_stmt->get_result();
            
            if ($result->num_rows > 0) {
                // Item exists in this store, just add the new quantity to the existing stock
                $row = $result->fetch_assoc();
                $new_quantity = $row['quantity'] + $quantity;
                $update_stmt = $conn->prepare("UPDATE inventory_stock SET quantity = ? WHERE id = ?");
                $update_stmt->bind_param("ii", $new_quantity, $row['id']);
                $update_stmt->execute();
                $update_stmt->close();
                $message = "<div class='alert alert-success'><i class='fa-solid fa-boxes-packing'></i> Stock updated successfully! Added $quantity units to the existing inventory.</div>";
            } else {
                // First time this item is being stocked in this specific store
                $insert_stmt = $conn->prepare("INSERT INTO inventory_stock (service_id, location_id, quantity) VALUES (?, ?, ?)");
                $insert_stmt->bind_param("iii", $service_id, $location_id, $quantity);
                $insert_stmt->execute();
                $insert_stmt->close();
                $message = "<div class='alert alert-success'><i class='fa-solid fa-check-circle'></i> Item successfully allocated to the store with an initial stock of $quantity units.</div>";
            }
            $check_stmt->close();
            $conn->commit();
        } catch (Exception $e) {
            $conn->rollback();
            $message = "<div class='alert alert-danger'><i class='fa-solid fa-triangle-exclamation'></i> Database Error: " . $e->getMessage() . "</div>";
        }
    } else {
         $message = "<div class='alert alert-danger'><i class='fa-solid fa-circle-exclamation'></i> Please select a valid location, an item from the pool, and enter a quantity.</div>";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pull from Central Pool | Enterprise Stores</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
    :root { --sidebar-width: 240px; --e-blue: #1e3a8a; --e-green: #16a34a; --bg: #f8fafc; --border: #e2e8f0; --text: #334155; }
    body { font-family: "Segoe UI", system-ui, sans-serif; background: var(--bg); margin: 0; padding: 0; color: var(--text); overflow-x: hidden; }
    
    .page-wrapper { position: absolute; top: 0; left: var(--sidebar-width); width: calc(100% - var(--sidebar-width)); min-height: 100vh; padding: 30px; box-sizing: border-box; }
    
    .header-bar { display: flex; justify-content: space-between; align-items: flex-end; margin-bottom: 25px; padding-bottom: 15px; border-bottom: 2px solid var(--border); }
    .header-bar h2 { color: #0f172a; margin: 0; font-size: 24px; font-weight: 800; display:flex; align-items:center; gap:10px; }

    .alert { padding: 15px 20px; border-radius: 8px; margin-bottom: 20px; font-weight: 600; display:flex; align-items:center; gap:10px; border-left: 5px solid; }
    .alert-success { background: #dcfce7; color: #166534; border-color: #22c55e; }
    .alert-danger { background: #fee2e2; color: #991b1b; border-color: #ef4444; }

    .form-card { background: #fff; border-radius: 12px; border: 1px solid var(--border); box-shadow: 0 4px 15px rgba(0,0,0,0.02); overflow: hidden; max-width: 800px; margin: 0 auto; }
    .card-header { background: #0284c7; padding: 20px 25px; color: #fff; font-size: 16px; font-weight: 800; text-transform: uppercase; display: flex; align-items: center; gap: 10px; }
    .card-body { padding: 30px; }
    
    .form-group { margin-bottom: 20px; display: flex; flex-direction: column; gap: 8px; }
    .form-group label { font-size: 13px; font-weight: 700; color: #475569; text-transform: uppercase; }
    .form-control { padding: 12px 15px; border: 1px solid #cbd5e1; border-radius: 8px; font-size: 15px; outline: none; transition: 0.2s; background: #f8fafc; }
    .form-control:focus { border-color: #0284c7; box-shadow: 0 0 0 3px #e0f2fe; background: #fff; }
    
    .card-footer { padding: 20px 30px; background: #f8fafc; border-top: 1px solid var(--border); display: flex; justify-content: flex-end; gap: 15px; }
    .btn { padding: 12px 25px; border-radius: 8px; font-weight: 800; cursor: pointer; font-size: 14px; transition: 0.2s; border: none; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; }
    .btn-secondary { background: #e2e8f0; color: #475569; }
    .btn-secondary:hover { background: #cbd5e1; }
    .btn-primary { background: #0284c7; color: #fff; box-shadow: 0 4px 6px rgba(2, 132, 199, 0.2); }
    .btn-primary:hover { background: #0369a1; transform: translateY(-1px); }
</style>
</head>
<body>

<?php include('../../../dripend/statpages/sidebar.php'); ?>

<div class="page-wrapper">

    <div style="margin-bottom:15px; max-width: 800px; margin-left: auto; margin-right: auto;">
        <a href="manageProducts.php" style="color:#64748b; text-decoration:none; font-weight:700; font-size:13px;"><i class="fa-solid fa-arrow-left"></i> Back to Stores Dashboard</a>
    </div>

    <div class="form-card">
        <div class="card-header"><i class="fa-solid fa-cloud-arrow-down"></i> Pull Item from Central Catalog to Store</div>
        
        <form method="post">
            <div class="card-body">
                <?= $message ?>
                
                <div class="alert" style="background:#eff6ff; color:#1e40af; border-color:#bfdbfe;">
                    <i class="fa-solid fa-info-circle"></i> Use this form to allocate an existing physical product from the Master Catalog into a specific physical location.
                </div>

                <div class="form-group">
                    <label>1. Select Receiving Location</label>
                    <select name="location_id" class="form-control" style="border-color:#0284c7; font-weight:bold;" required>
                        <option value="">-- Choose Store or Dispensary --</option>
                        <?php foreach($locations as $loc): ?>
                            <option value="<?= $loc['id'] ?>"><?= htmlspecialchars($loc['location_name']) ?> [<?= $loc['location_type'] ?>]</option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="form-group">
                    <label>2. Select Item from Central Pool</label>
                    <select name="service_id" class="form-control" required>
                        <option value="">-- Search and Select Item --</option>
                        <?php foreach($catalog_items as $item): ?>
                            <option value="<?= $item['id'] ?>">
                                <?= htmlspecialchars($item['service_name']) ?> | <?= htmlspecialchars($item['category_name']) ?> (Base: <?= htmlspecialchars($item['unit_of_pricing']) ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="form-group">
                    <label>3. Initial Quantity Received (In Base Units)</label>
                    <input type="number" name="quantity" class="form-control" min="0" value="0" style="font-size:18px; font-weight:bold; color:#16a34a;" required>
                </div>
            </div>
            
            <div class="card-footer">
                <a href="manage_products.php" class="btn btn-secondary">Cancel</a>
                <button type="submit" class="btn btn-primary"><i class="fa-solid fa-download"></i> Allocate to Store</button>
            </div>
        </form>
    </div>

</div>

</body>
</html>