<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/menu_config.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
}

// Handle purchase order operations
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $response = ['success' => false, 'message' => ''];
    
    try {
        if (isset($_POST['action'])) {
            switch ($_POST['action']) {
                case 'create_po':
                    $supplier_id = $_POST['supplier_id'];
                    $order_date = $_POST['order_date'];
                    $expected_delivery = $_POST['expected_delivery'] ?: null;
                    $notes = trim($_POST['notes']);
                    $items = json_decode($_POST['items'], true);
                    
                    if (empty($items)) {
                        $response['message'] = 'Please add at least one item to the purchase order';
                        break;
                    }
                    
                    $conn->begin_transaction();
                    
                    try {
                        // Insert purchase order
                        $po_sql = "INSERT INTO purchase_orders (supplier_id, order_date, expected_delivery, notes, created_by) 
                                  VALUES (?, ?, ?, ?, ?)";
                        $po_stmt = $conn->prepare($po_sql);
                        $po_stmt->bind_param("isssi", $supplier_id, $order_date, $expected_delivery, $notes, $user_id);
                        $po_stmt->execute();
                        
                        $po_id = $conn->insert_id;
                        
                        // Insert purchase order items
                        $item_sql = "INSERT INTO purchase_order_items (po_id, item_id, quantity, unit_cost, total_cost) 
                                    VALUES (?, ?, ?, ?, ?)";
                        $item_stmt = $conn->prepare($item_sql);
                        
                        $subtotal = 0;
                        foreach ($items as $item) {
                            $total_cost = $item['quantity'] * $item['unit_cost'];
                            $subtotal += $total_cost;
                            
                            $item_stmt->bind_param("iiddd", $po_id, $item['item_id'], $item['quantity'], $item['unit_cost'], $total_cost);
                            $item_stmt->execute();
                        }
                        
                        // Update purchase order totals
                        $update_sql = "UPDATE purchase_orders SET subtotal = ?, total_amount = ? WHERE po_id = ?";
                        $update_stmt = $conn->prepare($update_sql);
                        $update_stmt->bind_param("ddi", $subtotal, $subtotal, $po_id);
                        $update_stmt->execute();
                        
                        $conn->commit();
                        $response['success'] = true;
                        $response['message'] = 'Purchase order created successfully';
                        $response['po_id'] = $po_id;
                        
                    } catch (Exception $e) {
                        $conn->rollback();
                        throw $e;
                    }
                    break;
                    
                case 'update_status':
                    $po_id = $_POST['po_id'];
                    $status = $_POST['status'];
                    $notes = trim($_POST['notes']) ?: null;
                    
                    $conn->begin_transaction();
                    
                    try {
                        $update_sql = "UPDATE purchase_orders SET status = ?";
                        $params = [$status];
                        $types = "s";
                        
                        if ($notes) {
                            $update_sql .= ", notes = CONCAT(COALESCE(notes, ''), ?, ?)";
                            $params[] = "\n\nStatus Update: ";
                            $params[] = $notes;
                            $types .= "ss";
                        }
                        
                        $update_sql .= " WHERE po_id = ?";
                        $params[] = $po_id;
                        $types .= "i";
                        
                        $update_stmt = $conn->prepare($update_sql);
                        $update_stmt->bind_param($types, ...$params);
                        $update_stmt->execute();
                        
                        // If status is RECEIVED, update inventory
                        if ($status === 'RECEIVED') {
                            $items_sql = "SELECT poi.item_id, poi.quantity, poi.unit_cost 
                                         FROM purchase_order_items poi 
                                         WHERE poi.po_id = ?";
                            $items_stmt = $conn->prepare($items_sql);
                            $items_stmt->bind_param("i", $po_id);
                            $items_stmt->execute();
                            $items_result = $items_stmt->get_result();
                            
                            while ($item = $items_result->fetch_assoc()) {
                                // Get current stock
                                $current_stock_sql = "SELECT current_stock FROM inventory_items WHERE item_id = ?";
                                $cs_stmt = $conn->prepare($current_stock_sql);
                                $cs_stmt->bind_param("i", $item['item_id']);
                                $cs_stmt->execute();
                                $current_stock = $cs_stmt->get_result()->fetch_assoc()['current_stock'];
                                
                                $new_balance = $current_stock + $item['quantity'];
                                $total_value = $item['quantity'] * $item['unit_cost'];
                                
                                // Insert stock movement
                                $sm_sql = "INSERT INTO stock_movements (item_id, movement_type, reference_type, reference_id, quantity, unit_cost, total_value, balance_after, moved_by) 
                                          VALUES (?, 'IN', 'PURCHASE', ?, ?, ?, ?, ?, ?)";
                                $sm_stmt = $conn->prepare($sm_sql);
                                $sm_stmt->bind_param("iiddddi", $item['item_id'], $po_id, $item['quantity'], $item['unit_cost'], $total_value, $new_balance, $user_id);
                                $sm_stmt->execute();
                            }
                        }
                        
                        $conn->commit();
                        $response['success'] = true;
                        $response['message'] = 'Purchase order status updated successfully';
                        
                    } catch (Exception $e) {
                        $conn->rollback();
                        throw $e;
                    }
                    break;
                    
                case 'cancel_po':
                    $po_id = $_POST['po_id'];
                    $reason = trim($_POST['reason']);
                    
                    $cancel_sql = "UPDATE purchase_orders SET 
                                  status = 'CANCELLED', 
                                  notes = CONCAT(COALESCE(notes, ''), ?, ?) 
                                  WHERE po_id = ?";
                    $cancel_stmt = $conn->prepare($cancel_sql);
                    $cancel_reason = "\n\nCancelled on " . date('Y-m-d H:i:s') . ": ";
                    $cancel_stmt->bind_param("ssi", $cancel_reason, $reason, $po_id);
                    
                    if ($cancel_stmt->execute()) {
                        $response['success'] = true;
                        $response['message'] = 'Purchase order cancelled successfully';
                    } else {
                        $response['message'] = 'Failed to cancel purchase order';
                    }
                    break;
            }
        }
    } catch (Exception $e) {
        $response['message'] = 'Error: ' . $e->getMessage();
    }
    
    header('Content-Type: application/json');
    echo json_encode($response);
    exit();
}

// Get purchase order statistics
$sql_total_pos = "SELECT COUNT(*) as total_pos FROM purchase_orders";
$total_pos = $conn->query($sql_total_pos)->fetch_assoc()['total_pos'];

$sql_draft_pos = "SELECT COUNT(*) as draft_pos FROM purchase_orders WHERE status = 'DRAFT'";
$draft_pos = $conn->query($sql_draft_pos)->fetch_assoc()['draft_pos'];

$sql_pending_pos = "SELECT COUNT(*) as pending_pos FROM purchase_orders WHERE status IN ('SENT', 'CONFIRMED')";
$pending_pos = $conn->query($sql_pending_pos)->fetch_assoc()['pending_pos'];

$sql_received_pos = "SELECT COUNT(*) as received_pos FROM purchase_orders WHERE status = 'RECEIVED'";
$received_pos = $conn->query($sql_received_pos)->fetch_assoc()['received_pos'];

$sql_total_value = "SELECT COALESCE(SUM(total_amount), 0) as total_value FROM purchase_orders WHERE status != 'CANCELLED'";
$total_value = $conn->query($sql_total_value)->fetch_assoc()['total_value'];

// Get purchase orders with supplier information
$sql_purchase_orders = "SELECT 
    po.*,
    s.supplier_name,
    s.contact_person,
    s.phone,
    s.email,
    u.full_name as created_by_name,
    ua.full_name as approved_by_name,
    COUNT(poi.poi_id) as item_count
FROM purchase_orders po
LEFT JOIN suppliers s ON po.supplier_id = s.supplier_id
LEFT JOIN users u ON po.created_by = u.user_id
LEFT JOIN users ua ON po.approved_by = ua.user_id
LEFT JOIN purchase_order_items poi ON po.po_id = poi.po_id
GROUP BY po.po_id
ORDER BY po.created_at DESC";
$result_purchase_orders = $conn->query($sql_purchase_orders);

// Get suppliers for dropdown
$sql_suppliers = "SELECT supplier_id, supplier_name FROM suppliers WHERE is_active = 1 ORDER BY supplier_name";
$result_suppliers = $conn->query($sql_suppliers);

// Get inventory items for dropdown
$sql_inventory_items = "SELECT 
    ii.item_id, 
    ii.item_name, 
    ii.item_code, 
    ii.unit_cost,
    ii.unit,
    ic.category_name
FROM inventory_items ii
LEFT JOIN inventory_categories ic ON ii.category_id = ic.category_id
WHERE ii.is_active = 1 
ORDER BY ii.item_name";
$result_inventory_items = $conn->query($sql_inventory_items);

// Get recent purchase order activities
$sql_recent_activities = "SELECT 
    po.po_number,
    po.status,
    po.total_amount,
    po.order_date,
    po.updated_at,
    s.supplier_name,
    u.full_name as action_by
FROM purchase_orders po
JOIN suppliers s ON po.supplier_id = s.supplier_id
LEFT JOIN users u ON po.created_by = u.user_id
ORDER BY po.updated_at DESC
LIMIT 10";
$result_activities = $conn->query($sql_recent_activities);

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Purchase Orders - Laundry System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-header {
            background: linear-gradient(135deg, #7c3aed 0%, #a855f7 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            transition: all 0.2s ease;
        }
        
        .stat-card:hover {
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            transform: translateY(-1px);
        }
        
        .stat-title {
            font-size: 0.875rem;
            font-weight: 500;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            margin-bottom: 0.5rem;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-change {
            font-size: 0.875rem;
            font-weight: 500;
        }
        
        .table-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
            margin-bottom: 2rem;
        }
        
        .table-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .table-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }
        
        .data-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.875rem;
            color: #64748b;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .data-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            font-size: 0.875rem;
        }
        
        .data-table tbody tr:hover {
            background: #f8fafc;
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .status-draft { background: #f3f4f6; color: #374151; }
        .status-sent { background: #dbeafe; color: #1d4ed8; }
        .status-confirmed { background: #fef3c7; color: #92400e; }
        .status-received { background: #dcfce7; color: #166534; }
        .status-cancelled { background: #fee2e2; color: #991b1b; }
        
        .btn-primary {
            background: #7c3aed;
            border-color: #7c3aed;
        }
        
        .btn-primary:hover {
            background: #6d28d9;
            border-color: #6d28d9;
        }
        
        .action-buttons {
            display: flex;
            gap: 0.5rem;
        }
        
        .action-btn {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            border: none;
            font-size: 0.75rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .search-filter-bar {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
        }
        
        .filter-group {
            display: flex;
            gap: 1rem;
            align-items: end;
            flex-wrap: wrap;
        }
        
        .item-row {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            background: #f8fafc;
        }
        
        @media (max-width: 768px) {
            .stats-row {
                grid-template-columns: 1fr;
            }
            
            .filter-group {
                flex-direction: column;
                align-items: stretch;
            }
            
            .action-buttons {
                flex-direction: column;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h2 class="mb-2">Purchase Orders</h2>
                                <p class="mb-0">Create and manage purchase orders for inventory procurement</p>
                            </div>
                            <div class="d-flex gap-2">
                                <button type="button" class="btn btn-light" data-bs-toggle="modal" data-bs-target="#createPOModal">
                                    <i class="bi bi-plus-circle me-2"></i>Create Purchase Order
                                </button>
                                <button type="button" class="btn btn-outline-light" onclick="exportData()">
                                    <i class="bi bi-download me-2"></i>Export
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-title">Total Orders</div>
                            <div class="stat-value"><?php echo number_format($total_pos); ?></div>
                            <div class="stat-change" style="color: #7c3aed;">All purchase orders</div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Draft Orders</div>
                            <div class="stat-value" style="color: #64748b;"><?php echo number_format($draft_pos); ?></div>
                            <div class="stat-change" style="color: #64748b;">Pending completion</div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Pending Delivery</div>
                            <div class="stat-value" style="color: <?php echo $pending_pos > 0 ? '#d97706' : '#64748b'; ?>;">
                                <?php echo number_format($pending_pos); ?>
                            </div>
                            <div class="stat-change" style="color: #64748b;">Awaiting receipt</div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Total Value</div>
                            <div class="stat-value" style="color: #059669;">KES <?php echo number_format($total_value); ?></div>
                            <div class="stat-change" style="color: #64748b;">Active orders</div>
                        </div>
                    </div>

                    <!-- Search and Filter -->
                    <div class="search-filter-bar">
                        <div class="filter-group">
                            <div>
                                <label class="form-label">Search Orders</label>
                                <input type="text" class="form-control" id="searchInput" placeholder="Search by PO number, supplier...">
                            </div>
                            <div>
                                <label class="form-label">Status</label>
                                <select class="form-select" id="statusFilter">
                                    <option value="">All Status</option>
                                    <option value="DRAFT">Draft</option>
                                    <option value="SENT">Sent</option>
                                    <option value="CONFIRMED">Confirmed</option>
                                    <option value="RECEIVED">Received</option>
                                    <option value="CANCELLED">Cancelled</option>
                                </select>
                            </div>
                            <div>
                                <label class="form-label">Supplier</label>
                                <select class="form-select" id="supplierFilter">
                                    <option value="">All Suppliers</option>
                                    <?php
                                    $result_suppliers->data_seek(0);
                                    while($row = $result_suppliers->fetch_assoc()): ?>
                                        <option value="<?php echo htmlspecialchars($row['supplier_name']); ?>">
                                            <?php echo htmlspecialchars($row['supplier_name']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div>
                                <label class="form-label">&nbsp;</label>
                                <button type="button" class="btn btn-primary d-block" onclick="filterTable()">
                                    <i class="bi bi-search"></i> Filter
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Purchase Orders Table -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">Purchase Orders</h3>
                            <div>
                                <button type="button" class="btn btn-outline-primary btn-sm" onclick="refreshTable()">
                                    <i class="bi bi-arrow-clockwise me-1"></i>Refresh
                                </button>
                            </div>
                        </div>
                        <div class="table-responsive">
                            <table class="data-table" id="purchaseOrdersTable">
                                <thead>
                                    <tr>
                                        <th>PO Number</th>
                                        <th>Supplier</th>
                                        <th>Order Date</th>
                                        <th>Expected Delivery</th>
                                        <th>Items</th>
                                        <th>Total Amount</th>
                                        <th>Status</th>
                                        <th>Created By</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while($row = $result_purchase_orders->fetch_assoc()): ?>
                                    <tr>
                                        <td>
                                            <span style="color: #7c3aed; font-weight: 600;">
                                                <?php echo $row['po_number']; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div>
                                                <div style="font-weight: 600;"><?php echo htmlspecialchars($row['supplier_name']); ?></div>
                                                <?php if($row['contact_person']): ?>
                                                    <small style="color: #64748b;"><?php echo htmlspecialchars($row['contact_person']); ?></small>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td style="color: #64748b;">
                                            <?php echo date('M j, Y', strtotime($row['order_date'])); ?>
                                        </td>
                                        <td style="color: #64748b;">
                                            <?php if($row['expected_delivery']): ?>
                                                <?php echo date('M j, Y', strtotime($row['expected_delivery'])); ?>
                                            <?php else: ?>
                                                <span style="color: #64748b;">Not set</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span style="font-weight: 600;"><?php echo number_format($row['item_count']); ?></span>
                                            <small style="color: #64748b;"> items</small>
                                        </td>
                                        <td style="font-weight: 600; color: #059669;">
                                            KES <?php echo number_format($row['total_amount'], 2); ?>
                                        </td>
                                        <td>
                                            <?php 
                                            $status_class = match(strtolower($row['status'])) {
                                                'draft' => 'status-draft',
                                                'sent' => 'status-sent',
                                                'confirmed' => 'status-confirmed',
                                                'received' => 'status-received',
                                                'cancelled' => 'status-cancelled',
                                                default => 'status-draft'
                                            };
                                            ?>
                                            <span class="status-badge <?php echo $status_class; ?>">
                                                <?php echo ucfirst($row['status']); ?>
                                            </span>
                                        </td>
                                        <td style="color: #64748b;">
                                            <?php echo htmlspecialchars($row['created_by_name']); ?>
                                        </td>
                                        <td>
                                            <div class="action-buttons">
                                                <button class="action-btn btn btn-sm btn-primary" onclick="viewPO(<?php echo $row['po_id']; ?>)" title="View Details">
                                                    <i class="bi bi-eye"></i>
                                                </button>
                                                <?php if($row['status'] === 'DRAFT'): ?>
                                                    <button class="action-btn btn btn-sm btn-success" onclick="updateStatus(<?php echo $row['po_id']; ?>, 'SENT')" title="Send to Supplier">
                                                        <i class="bi bi-send"></i>
                                                    </button>
                                                <?php endif; ?>
                                                <?php if($row['status'] === 'SENT'): ?>
                                                    <button class="action-btn btn btn-sm btn-warning" onclick="updateStatus(<?php echo $row['po_id']; ?>, 'CONFIRMED')" title="Confirm Order">
                                                        <i class="bi bi-check"></i>
                                                    </button>
                                                <?php endif; ?>
                                                <?php if($row['status'] === 'CONFIRMED'): ?>
                                                    <button class="action-btn btn btn-sm btn-info" onclick="updateStatus(<?php echo $row['po_id']; ?>, 'RECEIVED')" title="Mark as Received">
                                                        <i class="bi bi-check-circle"></i>
                                                    </button>
                                                <?php endif; ?>
                                                <?php if(in_array($row['status'], ['DRAFT', 'SENT'])): ?>
                                                    <button class="action-btn btn btn-sm btn-danger" onclick="cancelPO(<?php echo $row['po_id']; ?>)" title="Cancel">
                                                        <i class="bi bi-x-circle"></i>
                                                    </button>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Recent Activities -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">Recent Purchase Order Activities</h3>
                        </div>
                        <div class="table-responsive">
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>PO Number</th>
                                        <th>Supplier</th>
                                        <th>Status</th>
                                        <th>Amount</th>
                                        <th>Action By</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if($result_activities->num_rows > 0): ?>
                                        <?php while($row = $result_activities->fetch_assoc()): ?>
                                        <tr>
                                            <td style="color: #64748b;">
                                                <?php echo date('M j, Y g:i A', strtotime($row['updated_at'])); ?>
                                            </td>
                                            <td>
                                                <span style="font-weight: 600; color: #7c3aed;">
                                                    <?php echo $row['po_number']; ?>
                                                </span>
                                            </td>
                                            <td style="font-weight: 500;">
                                                <?php echo htmlspecialchars($row['supplier_name']); ?>
                                            </td>
                                            <td>
                                                <?php 
                                                $status_class = match(strtolower($row['status'])) {
                                                    'draft' => 'status-draft',
                                                    'sent' => 'status-sent',
                                                    'confirmed' => 'status-confirmed',
                                                    'received' => 'status-received',
                                                    'cancelled' => 'status-cancelled',
                                                    default => 'status-draft'
                                                };
                                                ?>
                                                <span class="status-badge <?php echo $status_class; ?>">
                                                    <?php echo ucfirst($row['status']); ?>
                                                </span>
                                            </td>
                                            <td style="font-weight: 600;">
                                                KES <?php echo number_format($row['total_amount'], 2); ?>
                                            </td>
                                            <td style="color: #64748b;">
                                                <?php echo htmlspecialchars($row['action_by']); ?>
                                            </td>
                                        </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="6" class="text-center" style="color: #64748b; padding: 2rem;">
                                                No recent activities found
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Create Purchase Order Modal -->
    <div class="modal fade" id="createPOModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Create Purchase Order</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="createPOForm">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Supplier <span class="text-danger">*</span></label>
                                    <select class="form-select" name="supplier_id" required>
                                        <option value="">Select supplier...</option>
                                        <?php
                                        $result_suppliers->data_seek(0);
                                        while($row = $result_suppliers->fetch_assoc()): ?>
                                            <option value="<?php echo $row['supplier_id']; ?>">
                                                <?php echo htmlspecialchars($row['supplier_name']); ?>
                                            </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="mb-3">
                                    <label class="form-label">Order Date <span class="text-danger">*</span></label>
                                    <input type="date" class="form-control" name="order_date" value="<?php echo date('Y-m-d'); ?>" required>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="mb-3">
                                    <label class="form-label">Expected Delivery</label>
                                    <input type="date" class="form-control" name="expected_delivery">
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Items <span class="text-danger">*</span></label>
                            <div id="itemsContainer">
                                <!-- Items will be added here dynamically -->
                            </div>
                            <button type="button" class="btn btn-outline-primary btn-sm mt-2" onclick="addItem()">
                                <i class="bi bi-plus"></i> Add Item
                            </button>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Notes</label>
                            <textarea class="form-control" name="notes" rows="3" placeholder="Optional notes for the supplier..."></textarea>
                        </div>

                        <div class="row">
                            <div class="col-md-6 offset-md-6">
                                <div class="bg-light p-3 rounded">
                                    <div class="d-flex justify-content-between mb-2">
                                        <span>Subtotal:</span>
                                        <span id="subtotalAmount">KES 0.00</span>
                                    </div>
                                    <div class="d-flex justify-content-between fw-bold">
                                        <span>Total:</span>
                                        <span id="totalAmount">KES 0.00</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Create Purchase Order</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Status Update Modal -->
    <div class="modal fade" id="statusModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="statusModalTitle">Update Status</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="statusForm">
                    <input type="hidden" name="po_id" id="status_po_id">
                    <input type="hidden" name="status" id="status_value">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Notes</label>
                            <textarea class="form-control" name="notes" rows="3" placeholder="Optional notes about this status change..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary" id="statusSubmitBtn">Update Status</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Cancel PO Modal -->
    <div class="modal fade" id="cancelModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Cancel Purchase Order</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="cancelForm">
                    <input type="hidden" name="po_id" id="cancel_po_id">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Reason for Cancellation <span class="text-danger">*</span></label>
                            <textarea class="form-control" name="reason" rows="3" required placeholder="Please provide a reason for cancelling this purchase order..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-danger">Cancel Purchase Order</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Alert Container -->
    <div id="alertContainer" style="position: fixed; top: 20px; right: 20px; z-index: 9999;"></div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
    // Global variables
    let inventoryItems = <?php 
        $result_inventory_items->data_seek(0);
        $items = [];
        while($row = $result_inventory_items->fetch_assoc()) {
            $items[] = $row;
        }
        echo json_encode($items);
    ?>;
    
    let itemCounter = 0;

    // Form submission handlers
    document.getElementById('createPOForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const items = collectItems();
        if (items.length === 0) {
            showAlert('error', 'Please add at least one item to the purchase order');
            return;
        }
        
        const formData = new FormData(this);
        formData.append('action', 'create_po');
        formData.append('items', JSON.stringify(items));
        
        fetch('', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('success', data.message);
                bootstrap.Modal.getInstance(document.getElementById('createPOModal')).hide();
                setTimeout(() => window.location.reload(), 1000);
            } else {
                showAlert('error', data.message);
            }
        })
        .catch(error => {
            showAlert('error', 'An error occurred while creating purchase order');
        });
    });

    document.getElementById('statusForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        formData.append('action', 'update_status');
        
        fetch('', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('success', data.message);
                bootstrap.Modal.getInstance(document.getElementById('statusModal')).hide();
                setTimeout(() => window.location.reload(), 1000);
            } else {
                showAlert('error', data.message);
            }
        })
        .catch(error => {
            showAlert('error', 'An error occurred while updating status');
        });
    });

    document.getElementById('cancelForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        formData.append('action', 'cancel_po');
        
        fetch('', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('success', data.message);
                bootstrap.Modal.getInstance(document.getElementById('cancelModal')).hide();
                setTimeout(() => window.location.reload(), 1000);
            } else {
                showAlert('error', data.message);
            }
        })
        .catch(error => {
            showAlert('error', 'An error occurred while cancelling purchase order');
        });
    });

    // Item management functions
    function addItem() {
        itemCounter++;
        const container = document.getElementById('itemsContainer');
        
        const itemDiv = document.createElement('div');
        itemDiv.className = 'item-row';
        itemDiv.id = `item-${itemCounter}`;
        
        itemDiv.innerHTML = `
            <div class="row align-items-end">
                <div class="col-md-4">
                    <label class="form-label">Item</label>
                    <select class="form-select item-select" data-counter="${itemCounter}" required>
                        <option value="">Select item...</option>
                        ${inventoryItems.map(item => 
                            `<option value="${item.item_id}" data-cost="${item.unit_cost}" data-unit="${item.unit}">
                                ${item.item_name} (${item.item_code})
                            </option>`
                        ).join('')}
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Quantity</label>
                    <input type="number" class="form-control quantity-input" data-counter="${itemCounter}" step="0.01" min="0.01" required>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Unit Cost</label>
                    <input type="number" class="form-control cost-input" data-counter="${itemCounter}" step="0.01" min="0.01" required>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Total</label>
                    <input type="text" class="form-control total-display" data-counter="${itemCounter}" readonly>
                </div>
                <div class="col-md-1">
                    <label class="form-label">Unit</label>
                    <span class="form-control-plaintext unit-display" data-counter="${itemCounter}">-</span>
                </div>
                <div class="col-md-1">
                    <button type="button" class="btn btn-danger btn-sm" onclick="removeItem(${itemCounter})">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </div>
        `;
        
        container.appendChild(itemDiv);
        
        // Add event listeners
        const itemSelect = itemDiv.querySelector('.item-select');
        const quantityInput = itemDiv.querySelector('.quantity-input');
        const costInput = itemDiv.querySelector('.cost-input');
        
        itemSelect.addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            if (selectedOption.value) {
                const cost = selectedOption.dataset.cost;
                const unit = selectedOption.dataset.unit;
                costInput.value = cost;
                itemDiv.querySelector('.unit-display').textContent = unit;
                calculateItemTotal(itemCounter);
            }
        });
        
        quantityInput.addEventListener('input', () => calculateItemTotal(itemCounter));
        costInput.addEventListener('input', () => calculateItemTotal(itemCounter));
    }

    function removeItem(counter) {
        const itemDiv = document.getElementById(`item-${counter}`);
        if (itemDiv) {
            itemDiv.remove();
            calculateGrandTotal();
        }
    }

    function calculateItemTotal(counter) {
        const itemDiv = document.getElementById(`item-${counter}`);
        if (!itemDiv) return;
        
        const quantity = parseFloat(itemDiv.querySelector('.quantity-input').value) || 0;
        const cost = parseFloat(itemDiv.querySelector('.cost-input').value) || 0;
        const total = quantity * cost;
        
        itemDiv.querySelector('.total-display').value = `KES ${total.toFixed(2)}`;
        calculateGrandTotal();
    }

    function calculateGrandTotal() {
        let grandTotal = 0;
        
        document.querySelectorAll('.total-display').forEach(input => {
            const value = input.value.replace('KES ', '').replace(',', '');
            grandTotal += parseFloat(value) || 0;
        });
        
        document.getElementById('subtotalAmount').textContent = `KES ${grandTotal.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}`;
        document.getElementById('totalAmount').textContent = `KES ${grandTotal.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}`;
    }

    function collectItems() {
        const items = [];
        
        document.querySelectorAll('.item-row').forEach(itemDiv => {
            const itemSelect = itemDiv.querySelector('.item-select');
            const quantityInput = itemDiv.querySelector('.quantity-input');
            const costInput = itemDiv.querySelector('.cost-input');
            
            if (itemSelect.value && quantityInput.value && costInput.value) {
                items.push({
                    item_id: parseInt(itemSelect.value),
                    quantity: parseFloat(quantityInput.value),
                    unit_cost: parseFloat(costInput.value)
                });
            }
        });
        
        return items;
    }

    // Action functions
    function viewPO(poId) {
        window.location.href = `view_purchase_order.php?id=${poId}`;
    }

    function updateStatus(poId, status) {
        const statusTitles = {
            'SENT': 'Send to Supplier',
            'CONFIRMED': 'Confirm Order',
            'RECEIVED': 'Mark as Received'
        };
        
        document.getElementById('status_po_id').value = poId;
        document.getElementById('status_value').value = status;
        document.getElementById('statusModalTitle').textContent = statusTitles[status];
        document.getElementById('statusSubmitBtn').textContent = statusTitles[status];
        
        const modal = new bootstrap.Modal(document.getElementById('statusModal'));
        modal.show();
    }

    function cancelPO(poId) {
        document.getElementById('cancel_po_id').value = poId;
        const modal = new bootstrap.Modal(document.getElementById('cancelModal'));
        modal.show();
    }

    // Utility functions
    function showAlert(type, message) {
        const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
        const alertHtml = `
            <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        document.getElementById('alertContainer').innerHTML = alertHtml;
        
        setTimeout(() => {
            const alert = document.querySelector('#alertContainer .alert');
            if (alert) {
                bootstrap.Alert.getInstance(alert).close();
            }
        }, 5000);
    }

    function filterTable() {
        const searchTerm = document.getElementById('searchInput').value.toLowerCase();
        const statusFilter = document.getElementById('statusFilter').value;
        const supplierFilter = document.getElementById('supplierFilter').value;
        const table = document.getElementById('purchaseOrdersTable');
        const rows = table.getElementsByTagName('tbody')[0].getElementsByTagName('tr');

        for (let i = 0; i < rows.length; i++) {
            let show = true;
            const row = rows[i];
            const cells = row.getElementsByTagName('td');
            
            if (searchTerm) {
                const poNumber = cells[0].textContent.toLowerCase();
                const supplier = cells[1].textContent.toLowerCase();
                if (!poNumber.includes(searchTerm) && !supplier.includes(searchTerm)) {
                    show = false;
                }
            }
            
            if (statusFilter && show) {
                const status = cells[6].textContent.trim().toUpperCase();
                if (status !== statusFilter) {
                    show = false;
                }
            }
            
            if (supplierFilter && show) {
                const supplier = cells[1].textContent.trim();
                if (!supplier.includes(supplierFilter)) {
                    show = false;
                }
            }
            
            row.style.display = show ? '' : 'none';
        }
    }

    function refreshTable() {
        window.location.reload();
    }

    function exportData() {
        const table = document.getElementById('purchaseOrdersTable');
        const rows = table.querySelectorAll('tr');
        let csv = [];
        
        for (let i = 0; i < rows.length; i++) {
            const row = rows[i];
            const cols = row.querySelectorAll('td, th');
            let csvRow = [];
            
            for (let j = 0; j < cols.length - 1; j++) {
                csvRow.push('"' + cols[j].textContent.trim().replace(/"/g, '""') + '"');
            }
            csv.push(csvRow.join(','));
        }
        
        const csvContent = csv.join('\n');
        const blob = new Blob([csvContent], { type: 'text/csv' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'purchase_orders_' + new Date().toISOString().split('T')[0] + '.csv';
        a.click();
        window.URL.revokeObjectURL(url);
    }

    // Initialize
    document.addEventListener('DOMContentLoaded', function() {
        // Add initial item row
        addItem();
        
        // Real-time search
        document.getElementById('searchInput').addEventListener('input', filterTable);
        document.getElementById('statusFilter').addEventListener('change', filterTable);
        document.getElementById('supplierFilter').addEventListener('change', filterTable);
        
        // Reset modal forms when hidden
        document.getElementById('createPOModal').addEventListener('hidden.bs.modal', function() {
            document.getElementById('createPOForm').reset();
            document.getElementById('itemsContainer').innerHTML = '';
            itemCounter = 0;
            addItem();
            calculateGrandTotal();
        });
    });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>