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

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

if (!isset($_GET['po_id']) || empty($_GET['po_id'])) {
    header("Location: managePurchaseOrder.php");
    exit;
}

$po_id = (int)$_GET['po_id'];
$message = '';

// ==============================================================================
// 1. FETCH PO HEADER
// ==============================================================================
$stmt = $conn->prepare("SELECT * FROM purchase_orders WHERE id = ? AND status IN ('Approved', 'Partially Received')");
$stmt->bind_param("i", $po_id);
$stmt->execute();
$po = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$po) {
    die("<div style='padding:50px; text-align:center; font-family:sans-serif;'><h2>Invalid Request</h2><p>This Purchase Order is either not found, not approved yet, or has already been fully received.</p><a href='managePurchaseOrder.php'>Go Back</a></div>");
}

$location_id = $po['location_id']; // Crucial: Where the stock is going

// ==============================================================================
// 2. PROCESS RECEIVING SUBMISSION
// ==============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $item_ids = $_POST['item_id'] ?? [];
    $service_ids = $_POST['service_id'] ?? [];
    $receive_qtys = $_POST['receive_qty'] ?? [];
    $actual_costs = $_POST['actual_cost'] ?? [];
    $batch_nos = $_POST['batch_no'] ?? [];
    $expiry_dates = $_POST['expiry_date'] ?? [];

    $conn->begin_transaction();
    try {
        $total_items_processed = 0;

        foreach ($item_ids as $index => $poi_id) {
            $qty_received_now = (int)$receive_qtys[$index];
            if ($qty_received_now > 0) {
                $service_id = (int)$service_ids[$index];
                $unit_cost = (float)$actual_costs[$index];
                $batch = trim($batch_nos[$index]);
                $expiry = !empty($expiry_dates[$index]) ? $expiry_dates[$index] : null;

                // 1. Update PO Line Item (increment qty_received)
                $stmtLine = $conn->prepare("UPDATE purchase_order_items SET quantity_received = quantity_received + ? WHERE id = ?");
                $stmtLine->bind_param("ii", $qty_received_now, $poi_id);
                $stmtLine->execute();
                $stmtLine->close();

                // 2. Update Physical Store Inventory (inventory_stock)
                $checkStock = $conn->prepare("SELECT id, quantity FROM inventory_stock WHERE service_id = ? AND location_id = ?");
                $checkStock->bind_param("ii", $service_id, $location_id);
                $checkStock->execute();
                $stockResult = $checkStock->get_result();
                
                if ($stockResult->num_rows > 0) {
                    $stock_row = $stockResult->fetch_assoc();
                    $new_qty = $stock_row['quantity'] + $qty_received_now;
                    $updStock = $conn->prepare("UPDATE inventory_stock SET quantity = ? WHERE id = ?");
                    $updStock->bind_param("ii", $new_qty, $stock_row['id']);
                    $updStock->execute();
                    $updStock->close();
                } else {
                    $insStock = $conn->prepare("INSERT INTO inventory_stock (service_id, location_id, quantity) VALUES (?, ?, ?)");
                    $insStock->bind_param("iii", $service_id, $location_id, $qty_received_now);
                    $insStock->execute();
                    $insStock->close();
                }
                $checkStock->close();

                // 3. Write to Audit Ledger (inventory_transactions)
                $trans_type = 'Receive Goods';
                $stmtTrans = $conn->prepare("
                    INSERT INTO inventory_transactions (service_id, location_id, transaction_type, quantity_changed, batch_number, expiry_date, unit_cost, reference_id) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $stmtTrans->bind_param("iisisssi", $service_id, $location_id, $trans_type, $qty_received_now, $batch, $expiry, $unit_cost, $po_id);
                $stmtTrans->execute();
                $stmtTrans->close();

                $total_items_processed++;
            }
        }

        // 4. Check if the entire PO is now complete to update PO Status
        $checkPO = $conn->query("SELECT SUM(quantity_ordered) as total_ordered, SUM(quantity_received) as total_received FROM purchase_order_items WHERE po_id = $po_id");
        $po_totals = $checkPO->fetch_assoc();
        
        $new_status = 'Partially Received';
        if ($po_totals['total_received'] >= $po_totals['total_ordered']) {
            $new_status = 'Received';
        }

        $conn->query("UPDATE purchase_orders SET status = '$new_status' WHERE id = $po_id");

        $conn->commit();
        $message = "<div class='alert alert-success'><i class='fa-solid fa-check-double'></i> <strong>Success:</strong> $total_items_processed line items have been received into inventory.</div>";
        
        // Refresh PO data after updates
        $po['status'] = $new_status;

    } catch (Exception $e) {
        $conn->rollback();
        $message = "<div class='alert alert-danger'><i class='fa-solid fa-triangle-exclamation'></i> Error processing receipt: " . $e->getMessage() . "</div>";
    }
}

// ==============================================================================
// 3. FETCH PENDING PO LINE ITEMS
// ==============================================================================
// We only fetch items where quantity_received < quantity_ordered
$stmt_items = $conn->prepare("
    SELECT poi.*, sc.service_name, sc.unit_of_pricing 
    FROM purchase_order_items poi
    JOIN service_catalog sc ON poi.service_id = sc.id
    WHERE poi.po_id = ? AND poi.quantity_received < poi.quantity_ordered
");
$stmt_items->bind_param("i", $po_id);
$stmt_items->execute();
$pending_items = $stmt_items->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt_items->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Receive Goods | Enterprise Logistics</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; --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); }
    .page-wrapper { margin-left: var(--sidebar-width); padding: 30px; min-height: 100vh; box-sizing: border-box; width: calc(100% - var(--sidebar-width)); }
    
    .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: #0284c7; 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; }

    .info-panel { background: #fff; padding: 20px; border-radius: 12px; margin-bottom: 25px; border: 1px solid var(--border); border-left: 5px solid #0f172a; display: flex; justify-content: space-between; align-items: center; box-shadow: 0 4px 10px rgba(0,0,0,0.02); }
    
    .table-card { background: #fff; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); overflow-x: auto; border: 1px solid var(--border); }
    table { width: 100%; border-collapse: collapse; min-width: 1200px; }
    th { background: #f8fafc; color: #475569; padding: 15px; font-size: 12px; text-transform: uppercase; border-bottom: 2px solid var(--border); text-align: left; }
    td { padding: 10px 15px; border-bottom: 1px solid var(--border); font-size: 14px; vertical-align: middle; }
    
    .form-control { padding: 10px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 14px; outline: none; width: 100%; box-sizing: border-box; }
    .form-control:focus { border-color: #0284c7; box-shadow: 0 0 0 3px #e0f2fe; }
    
    .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;">
        <a href="managePurchaseOrder.php" style="color:#64748b; text-decoration:none; font-weight:700; font-size:13px;"><i class="fa-solid fa-arrow-left"></i> Back to Dashboard</a>
    </div>

    <div class="header-bar">
        <h2><i class="fa-solid fa-boxes-packing"></i> Goods Received Note (GRN)</h2>
    </div>

    <?= $message ?>

    <div class="info-panel">
        <div>
            <h3 style="margin:0 0 5px 0; color:#0f172a; font-size:18px;">PO Number: <?= htmlspecialchars($po['po_number']) ?></h3>
            <p style="margin:0; color:#64748b; font-size:14px; font-weight:600;"><i class="fa-solid fa-location-dot" style="color:#0284c7;"></i> Receiving Location ID: #<?= $po['location_id'] ?></p>
        </div>
        <div>
            <span style="background:#e0f2fe; color:#0369a1; padding:8px 15px; border-radius:8px; font-weight:800; font-size:14px; border:1px solid #bae6fd;">
                Status: <?= htmlspecialchars($po['status']) ?>
            </span>
        </div>
    </div>

    <?php if ($po['status'] === 'Received'): ?>
        <div style="text-align:center; padding:60px; background:#fff; border-radius:12px; border:1px solid var(--border);">
            <i class="fa-solid fa-check-circle" style="font-size:50px; color:#16a34a; margin-bottom:15px;"></i>
            <h2 style="color:#0f172a;">Order Fully Received</h2>
            <p style="color:#64748b; font-weight:600;">All items in this Purchase Order have been successfully logged into inventory.</p>
        </div>
    <?php else: ?>
        <form method="POST">
            <div class="table-card">
                <table>
                    <thead>
                        <tr>
                            <th style="width:25%;">Item & Brand</th>
                            <th style="width:10%; text-align:center;">Ordered</th>
                            <th style="width:10%; text-align:center;">Pending</th>
                            <th style="width:12%;">Receive Qty Now</th>
                            <th style="width:15%;">Batch No.</th>
                            <th style="width:15%;">Expiry Date</th>
                            <th style="width:13%;">Actual Cost (GHS)</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($pending_items as $item): 
                            $pending_qty = $item['quantity_ordered'] - $item['quantity_received'];
                        ?>
                        <tr>
                            <td>
                                <strong style="color:#0f172a; font-size:15px;"><?= htmlspecialchars($item['service_name']) ?></strong><br>
                                <span style="font-size:12px; color:#64748b; font-weight:700;">Brand: <?= htmlspecialchars($item['brand_name'] ?: 'Generic') ?></span>
                                <input type="hidden" name="item_id[]" value="<?= $item['id'] ?>">
                                <input type="hidden" name="service_id[]" value="<?= $item['service_id'] ?>">
                            </td>
                            <td style="text-align:center; font-weight:700; color:#475569;"><?= number_format($item['quantity_ordered']) ?></td>
                            <td style="text-align:center; font-weight:900; color:#b45309;"><?= number_format($pending_qty) ?></td>
                            <td>
                                <input type="number" name="receive_qty[]" class="form-control" style="font-weight:bold; color:#16a34a;" min="0" max="<?= $pending_qty ?>" value="<?= $pending_qty ?>" required>
                            </td>
                            <td>
                                <input type="text" name="batch_no[]" class="form-control" placeholder="e.g. BATCH-001" required>
                            </td>
                            <td>
                                <input type="date" name="expiry_date[]" class="form-control" required>
                            </td>
                            <td>
                                <input type="number" name="actual_cost[]" class="form-control" step="0.01" min="0" value="<?= $item['expected_unit_cost'] ?>" required>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <div style="display:flex; justify-content:flex-end; gap:15px; margin-top:20px; padding-bottom:30px;">
                <button type="submit" class="btn btn-primary"><i class="fa-solid fa-boxes-packing"></i> Confirm Receipt & Update Stock</button>
            </div>
        </form>
    <?php endif; ?>

</div>

</body>
</html>