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

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

$message = '';

// ==============================================================================
// 1. HANDLE POST ACTIONS (Approve or Cancel)
// ==============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $po_id = (int)$_POST['po_id'];
    $action = $_POST['action'];
    
    if ($action === 'approve') {
        $stmt = $conn->prepare("UPDATE purchase_orders SET status = 'Approved', approval_date = NOW() WHERE id = ? AND status = 'Pending'");
        $stmt->bind_param("i", $po_id);
        if ($stmt->execute() && $stmt->affected_rows > 0) {
            $message = "<div class='alert alert-success'><i class='fa-solid fa-check-double'></i> Purchase Order successfully Approved and authorized for delivery.</div>";
        }
        $stmt->close();
    } elseif ($action === 'cancel') {
        $stmt = $conn->prepare("UPDATE purchase_orders SET status = 'Cancelled' WHERE id = ? AND status IN ('Pending', 'Approved')");
        $stmt->bind_param("i", $po_id);
        if ($stmt->execute() && $stmt->affected_rows > 0) {
            $message = "<div class='alert alert-success'><i class='fa-solid fa-ban'></i> Purchase Order has been cancelled.</div>";
        }
        $stmt->close();
    }
}

// ==============================================================================
// 2. FETCH DICTIONARIES FOR FILTERS
// ==============================================================================
$suppliers = $conn->query("SELECT id, supplier_name FROM suppliers ORDER BY supplier_name ASC")->fetch_all(MYSQLI_ASSOC);
$stores = $conn->query("SELECT id, location_name FROM inventory_locations WHERE location_type = 'Store' ORDER BY location_name ASC")->fetch_all(MYSQLI_ASSOC);

// ==============================================================================
// 3. DYNAMIC SQL SEARCH & ADVANCED FILTERS
// ==============================================================================
$search_po = $_GET['po_number'] ?? '';
$filter_supplier = !empty($_GET['supplier_id']) ? (int)$_GET['supplier_id'] : null;
$filter_location = !empty($_GET['location_id']) ? (int)$_GET['location_id'] : null;
$filter_status = $_GET['status'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';

$query = "
    SELECT p.*, s.supplier_name, l.location_name 
    FROM purchase_orders p
    JOIN suppliers s ON p.supplier_id = s.id
    JOIN inventory_locations l ON p.location_id = l.id
    WHERE 1=1
";

$params = [];
$types = "";

if ($search_po !== '') {
    $query .= " AND p.po_number LIKE ? ";
    $params[] = "%{$search_po}%";
    $types .= "s";
}
if ($filter_supplier) {
    $query .= " AND p.supplier_id = ? ";
    $params[] = $filter_supplier;
    $types .= "i";
}
if ($filter_location) {
    $query .= " AND p.location_id = ? ";
    $params[] = $filter_location;
    $types .= "i";
}
if ($filter_status !== '') {
    $query .= " AND p.status = ? ";
    $params[] = $filter_status;
    $types .= "s";
}
if ($date_from !== '') {
    $query .= " AND p.order_date >= ? ";
    $params[] = $date_from;
    $types .= "s";
}
if ($date_to !== '') {
    $query .= " AND p.order_date <= ? ";
    $params[] = $date_to;
    $types .= "s";
}

$query .= " ORDER BY p.created_at DESC";

$stmt = $conn->prepare($query);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$purchase_orders = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// ==============================================================================
// 4. GLOBAL KPI CALCULATIONS
// ==============================================================================
$kpis = [
    'pending_approvals' => 0,
    'awaiting_delivery' => 0,
    'completed_orders' => 0,
    'capital_committed' => 0.00
];

// We fetch global KPIs separately so filters don't hide the big picture
$kpi_query = $conn->query("SELECT status, total_estimated_cost FROM purchase_orders");
while ($row = $kpi_query->fetch_assoc()) {
    if ($row['status'] == 'Pending') {
        $kpis['pending_approvals']++;
        $kpis['capital_committed'] += $row['total_estimated_cost'];
    } elseif ($row['status'] == 'Approved' || $row['status'] == 'Partially Received') {
        $kpis['awaiting_delivery']++;
        $kpis['capital_committed'] += $row['total_estimated_cost'];
    } elseif ($row['status'] == 'Received') {
        $kpis['completed_orders']++;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Manage Purchase Orders | Enterprise Procurement</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); }
    .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: #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; }

    .primary-actions { display: flex; gap: 12px; }
    .btn-action-top { padding: 12px 18px; text-decoration: none; border-radius: 8px; font-weight: bold; box-shadow: 0 4px 6px rgba(0,0,0,0.1); transition: 0.2s; display: inline-flex; align-items: center; gap: 8px; border:none; color:#fff; font-size:14px; cursor: pointer;}
    .btn-action-top:hover { transform: translateY(-2px); box-shadow: 0 6px 12px rgba(0,0,0,0.15); }
    .bg-add { background: #0f172a; }

    .kpi-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px; margin-bottom: 25px; }
    .kpi-card { background: #fff; padding: 20px; border-radius: 12px; border: 1px solid var(--border); border-left: 5px solid #0f172a; box-shadow: 0 4px 10px rgba(0,0,0,0.02); display: flex; justify-content: space-between; align-items: center; }
    .kpi-card.yellow { border-left-color: #f59e0b; }
    .kpi-card.blue { border-left-color: #0284c7; }
    .kpi-card.green { border-left-color: #16a34a; }
    .kpi-info h3 { margin: 0 0 5px 0; font-size: 12px; color: #64748b; text-transform: uppercase; font-weight: 800; }
    .kpi-info p { margin: 0; font-size: 24px; font-weight: 900; color: #0f172a; }
    .kpi-icon { font-size: 30px; color: #e2e8f0; }
    .kpi-card.yellow .kpi-icon { color: #fde68a; }

    .filter-panel { background: #fff; padding: 20px 25px; border-radius: 12px; margin-bottom: 25px; border: 1px solid var(--border); box-shadow: 0 4px 10px rgba(0,0,0,0.02); }
    .filter-header { font-size: 13px; font-weight: 800; color: #0f172a; text-transform: uppercase; margin-bottom: 15px; display: flex; align-items: center; gap: 8px; border-bottom: 1px dashed var(--border); padding-bottom: 10px; }
    .filter-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 15px; align-items: end; }
    .form-group { display: flex; flex-direction: column; gap: 6px; }
    .form-group label { font-size: 11px; font-weight: 800; color: #64748b; text-transform: uppercase; }
    .form-control { padding: 10px 12px; border-radius: 6px; border: 1px solid #cbd5e1; outline: none; font-size: 13px; background: #f8fafc; }
    .form-control:focus { border-color: #0f172a; box-shadow: 0 0 0 3px #e2e8f0; background: #fff; }
    .btn-filter { background: #0f172a; color: #fff; border: none; padding: 10px 20px; border-radius: 6px; font-weight: bold; cursor: pointer; transition: 0.2s; height: 38px; display: flex; align-items: center; justify-content: center; gap: 8px; }
    .btn-filter:hover { background: #1e293b; }

    .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: 1100px; }
    th { background: #f8fafc; color: #475569; padding: 15px; font-size: 12px; text-transform: uppercase; border-bottom: 2px solid var(--border); text-align: left; white-space: nowrap; font-weight:800; }
    td { padding: 15px; border-bottom: 1px solid var(--border); font-size: 14px; vertical-align: middle; }
    tr:hover { background: #f0f9ff; }
    
    .badge { padding: 5px 10px; border-radius: 6px; font-size: 11px; font-weight: 800; display: inline-flex; align-items: center; gap: 5px; white-space: nowrap; }
    .bg-pending { background: #fef3c7; color: #b45309; border: 1px solid #fde68a; }
    .bg-approved { background: #e0f2fe; color: #0369a1; border: 1px solid #bae6fd; }
    .bg-partial { background: #e0e7ff; color: #4338ca; border: 1px solid #c7d2fe; }
    .bg-received { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; }
    .bg-cancelled { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }

    .action-group { display: flex; gap: 6px; justify-content: flex-end; }
    .btn-action { height: 32px; padding: 0 12px; border-radius: 6px; border: none; display: inline-flex; align-items: center; justify-content: center; gap: 6px; cursor: pointer; transition: 0.2s; font-size: 12px; font-weight: 700; text-decoration: none; }
    .btn-view { background: #f1f5f9; color: #475569; border: 1px solid #cbd5e1; }
    .btn-view:hover { background: #e2e8f0; }
    .btn-approve { background: #16a34a; color: #fff; box-shadow: 0 2px 4px rgba(22,163,74,0.2); }
    .btn-approve:hover { background: #15803d; }
    .btn-receive { background: #0284c7; color: #fff; box-shadow: 0 2px 4px rgba(2,132,199,0.2); }
    .btn-receive:hover { background: #0369a1; }
    .btn-cancel { background: #fff; color: #dc2626; border: 1px solid #fca5a5; }
    .btn-cancel:hover { background: #fee2e2; }
</style>
</head>
<body>

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

<div class="page-wrapper">

    <div class="header-bar">
        <h2><i class="fa-solid fa-file-invoice-dollar" style="color:#0f172a;"></i> Purchase Orders Control</h2>
        <div class="primary-actions">
            <a href="create_po.php" class="btn-action-top bg-add"><i class="fa-solid fa-plus"></i> Generate New PO</a>
        </div>
    </div>

    <?= $message ?>

    <div class="kpi-grid">
        <div class="kpi-card yellow">
            <div class="kpi-info"><h3 style="color:#b45309;">Pending Approvals</h3><p><?= number_format($kpis['pending_approvals']) ?></p></div>
            <i class="fa-solid fa-clock-rotate-left kpi-icon"></i>
        </div>
        <div class="kpi-card blue">
            <div class="kpi-info"><h3>Awaiting Delivery</h3><p><?= number_format($kpis['awaiting_delivery']) ?></p></div>
            <i class="fa-solid fa-truck-fast kpi-icon"></i>
        </div>
        <div class="kpi-card green">
            <div class="kpi-info"><h3>Completed / Received</h3><p><?= number_format($kpis['completed_orders']) ?></p></div>
            <i class="fa-solid fa-box-check kpi-icon"></i>
        </div>
        <div class="kpi-card">
            <div class="kpi-info"><h3>Totoal Purchases</h3><p>GHS <?= number_format($kpis['capital_committed'], 2) ?></p></div>
            <i class="fa-solid fa-coins kpi-icon" style="color:#cbd5e1;"></i>
        </div>
    </div>

    <div class="filter-panel">
        <div class="filter-header"><i class="fa-solid fa-filter"></i> Advanced Search & Tracking Filters</div>
        <form method="GET" action="">
            <div class="filter-grid">
                <div class="form-group">
                    <label>PO Number</label>
                    <input type="text" name="po_number" class="form-control" placeholder="PO-2026-..." value="<?= htmlspecialchars($search_po) ?>">
                </div>
                <div class="form-group">
                    <label>Supplier</label>
                    <select name="supplier_id" class="form-control">
                        <option value="">All Suppliers</option>
                        <?php foreach($suppliers as $sup): ?>
                            <option value="<?= $sup['id'] ?>" <?= $filter_supplier == $sup['id'] ? 'selected' : '' ?>><?= htmlspecialchars($sup['supplier_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Destination Store</label>
                    <select name="location_id" class="form-control">
                        <option value="">All Stores</option>
                        <?php foreach($stores as $store): ?>
                            <option value="<?= $store['id'] ?>" <?= $filter_location == $store['id'] ? 'selected' : '' ?>><?= htmlspecialchars($store['location_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Order Status</label>
                    <select name="status" class="form-control">
                        <option value="">All Statuses</option>
                        <option value="Pending" <?= $filter_status == 'Pending' ? 'selected' : '' ?>>Pending Approval</option>
                        <option value="Approved" <?= $filter_status == 'Approved' ? 'selected' : '' ?>>Approved (Awaiting Delivery)</option>
                        <option value="Partially Received" <?= $filter_status == 'Partially Received' ? 'selected' : '' ?>>Partially Received</option>
                        <option value="Received" <?= $filter_status == 'Received' ? 'selected' : '' ?>>Received & Closed</option>
                        <option value="Cancelled" <?= $filter_status == 'Cancelled' ? 'selected' : '' ?>>Cancelled</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>From Date</label>
                    <input type="date" name="date_from" class="form-control" value="<?= htmlspecialchars($date_from) ?>">
                </div>
                <div class="form-group">
                    <label>To Date</label>
                    <input type="date" name="date_to" class="form-control" value="<?= htmlspecialchars($date_to) ?>">
                </div>
                <div class="form-group" style="flex-direction:row; gap:10px;">
                    <button type="submit" class="btn-filter" style="flex:1;"><i class="fa-solid fa-magnifying-glass"></i> Search</button>
                    <a href="managePurchaseOrder.php" class="btn-filter" style="background:#e2e8f0; color:#475569; text-decoration:none;"><i class="fa-solid fa-rotate-left"></i></a>
                </div>
            </div>
        </form>
    </div>

    <div class="table-card">
        <table>
            <thead>
                <tr>
                    <th>PO Number & Date</th>
                    <th>Supplier Details</th>
                    <th>Destination Store</th>
                    <th>Total Value (GHS)</th>
                    <th>Current Status</th>
                    <th style="text-align:right;">Logistics Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if(empty($purchase_orders)): ?>
                    <tr><td colspan="6" style="text-align:center; padding:40px; color:#94a3b8; font-weight:600;"><i class="fa-solid fa-folder-open" style="font-size:30px; margin-bottom:10px; display:block;"></i> No Purchase Orders found.</td></tr>
                <?php else: 
                    foreach ($purchase_orders as $po): 
                        // Determine Status Badge Styling
                        $badge_class = '';
                        $icon = '';
                        switch ($po['status']) {
                            case 'Pending': $badge_class = 'bg-pending'; $icon = 'fa-clock'; break;
                            case 'Approved': $badge_class = 'bg-approved'; $icon = 'fa-truck-arrow-right'; break;
                            case 'Partially Received': $badge_class = 'bg-partial'; $icon = 'fa-box-open'; break;
                            case 'Received': $badge_class = 'bg-received'; $icon = 'fa-check-double'; break;
                            case 'Cancelled': $badge_class = 'bg-cancelled'; $icon = 'fa-ban'; break;
                        }
                ?>
                <tr>
                    <td>
                        <strong style="color:#0f172a; font-size:15px; font-family:monospace;"><?= htmlspecialchars($po['po_number']) ?></strong><br>
                        <span style="font-size:12px; color:#64748b; font-weight:700;"><i class="fa-regular fa-calendar"></i> <?= date('d M Y', strtotime($po['order_date'])) ?></span>
                    </td>
                    <td style="font-weight:700; color:#0f172a;"><?= htmlspecialchars($po['supplier_name']) ?></td>
                    <td>
                        <span style="color:#0284c7; font-weight:800; font-size:13px;"><i class="fa-solid fa-location-dot"></i> <?= htmlspecialchars($po['location_name']) ?></span>
                    </td>
                    <td><strong style="color:#16a34a; font-size:15px;"><?= number_format($po['total_estimated_cost'], 2) ?></strong></td>
                    
                    <td><span class="badge <?= $badge_class ?>"><i class="fa-solid <?= $icon ?>"></i> <?= $po['status'] ?></span></td>
                    
                    <td style="text-align:right;">
                        <div class="action-group">
                            <a href="viewPO.php?id=<?= $po['id'] ?>" class="btn-action btn-view" title="View Document"><i class="fa-solid fa-eye"></i> View</a>
                            
                            <?php if ($po['status'] === 'Pending'): ?>
                                <button class="btn-action btn-approve" onclick="handlePOAction(<?= $po['id'] ?>, 'approve')"><i class="fa-solid fa-thumbs-up"></i> Approve</button>
                                <button class="btn-action btn-cancel" onclick="handlePOAction(<?= $po['id'] ?>, 'cancel')"><i class="fa-solid fa-xmark"></i></button>
                            <?php endif; ?>

                            <?php if ($po['status'] === 'Approved' || $po['status'] === 'Partially Received'): ?>
                                <a href="receivePO.php?po_id=<?= $po['id'] ?>" class="btn-action btn-receive"><i class="fa-solid fa-boxes-packing"></i> Receive Goods</a>
                                <button class="btn-action btn-cancel" onclick="handlePOAction(<?= $po['id'] ?>, 'cancel')"><i class="fa-solid fa-xmark"></i></button>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>

</div>

<form id="actionForm" method="POST" style="display:none;">
    <input type="hidden" name="po_id" id="actId">
    <input type="hidden" name="action" id="actAction">
</form>

<script>
function handlePOAction(id, action) {
    let msg = action === 'approve' ? "Are you sure you want to APPROVE this Purchase Order?" : "Are you sure you want to CANCEL this Purchase Order?";
    if (confirm(msg)) {
        document.getElementById('actId').value = id;
        document.getElementById('actAction').value = action;
        document.getElementById('actionForm').submit();
    }
}
</script>

</body>
</html>