<?php
require_once 'config.inc.php';
require_login();

// Sanitize status filter
$filter = $_GET['filter'] ?? 'all';
$validFilters = ['pending', 'partially_delivered', 'delivered', 'cancelled'];
if (!in_array($filter, $validFilters, true)) {
    $filter = 'all';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    check_csrf();
    $op = $_POST['op'] ?? '';

    if ($op === 'update_delivery') {
        $orderId = (int)($_POST['order_id'] ?? 0);
        $newStatus = $_POST['status'] ?? 'pending';
        $adminComment = trim($_POST['admin_comment'] ?? '');
        $itemDeliveredQty = $_POST['items'] ?? [];

        if (!$orderId || !in_array($newStatus, $validFilters, true)) {
            flash('danger', 'Invalid order update request.');
            redirect('orders.php' . ($filter !== 'all' ? '?filter=' . urlencode($filter) : ''));
        }

        $db = db();

        try {
            $db->begin_transaction();

            /*
             * Lock the order items and their products while calculating the
             * delivery difference. This prevents two admins from delivering
             * the same stock at the same time.
             */
            $itemStmt = $db->prepare("
                SELECT
                    oi.id,
                    oi.product_id,
                    oi.quantity,
                    oi.quantity_delivered,
                    p.quantity AS stock_quantity,
                    p.display_model
                FROM order_items oi
                JOIN products p ON p.id = oi.product_id
                WHERE oi.id = ? AND oi.order_id = ?
                FOR UPDATE
            ");

            $updateItemStmt = $db->prepare("
                UPDATE order_items
                SET quantity_delivered = ?
                WHERE id = ? AND order_id = ?
            ");

            $updateStockStmt = $db->prepare("
                UPDATE products
                SET quantity = quantity - ?
                WHERE id = ? AND quantity >= ?
            ");

            foreach ($itemDeliveredQty as $itemId => $requestedDelivered) {
                $itemId = (int)$itemId;
                $requestedDelivered = (int)$requestedDelivered;

                if ($itemId <= 0 || $requestedDelivered < 0) {
                    throw new Exception('Invalid delivered quantity.');
                }

                $itemStmt->bind_param("ii", $itemId, $orderId);
                $itemStmt->execute();
                $item = $itemStmt->get_result()->fetch_assoc();

                if (!$item) {
                    throw new Exception('One of the order items could not be found.');
                }

                $orderedQty = (int)$item['quantity'];
                $oldDelivered = (int)$item['quantity_delivered'];

                if ($requestedDelivered > $orderedQty) {
                    throw new Exception(
                        'Delivered quantity for ' . $item['display_model'] .
                        ' cannot exceed the ordered quantity of ' . $orderedQty . '.'
                    );
                }

                /*
                 * IMPORTANT:
                 * Only the difference is applied to stock.
                 *
                 * Example:
                 * old delivered = 2, new delivered = 5
                 * stock decreases by 3.
                 *
                 * If admin corrects 5 back to 3, stock increases by 2.
                 */
                $delta = $requestedDelivered - $oldDelivered;

                if ($delta > 0) {
                    $updateStockStmt->bind_param(
                        "iii",
                        $delta,
                        $item['product_id'],
                        $delta
                    );
                    $updateStockStmt->execute();

                    if ($updateStockStmt->affected_rows !== 1) {
                        throw new Exception(
                            'Insufficient stock for ' . $item['display_model'] .
                            '. Available stock: ' . (int)$item['stock_quantity'] . '.'
                        );
                    }
                } elseif ($delta < 0) {
                    $increase = abs($delta);
                    $restoreStmt = $db->prepare("
                        UPDATE products
                        SET quantity = quantity + ?
                        WHERE id = ?
                    ");
                    $restoreStmt->bind_param("ii", $increase, $item['product_id']);
                    $restoreStmt->execute();
                    $restoreStmt->close();
                }

                $updateItemStmt->bind_param(
                    "iii",
                    $requestedDelivered,
                    $itemId,
                    $orderId
                );
                $updateItemStmt->execute();
            }

            $itemStmt->close();
            $updateItemStmt->close();
            $updateStockStmt->close();

            $s = $db->prepare("
                UPDATE orders
                SET status = ?, admin_comment = ?
                WHERE id = ?
            ");
            $s->bind_param("ssi", $newStatus, $adminComment, $orderId);
            $s->execute();
            $s->close();

            $db->commit();

            $statusText = ucwords(str_replace('_', ' ', $newStatus));
            flash(
                'success',
                "Order #{$orderId} updated successfully to {$statusText}. Stock was adjusted according to the delivery changes."
            );
        } catch (Throwable $e) {
            try {
                $db->rollback();
            } catch (Throwable $ignored) {}

            error_log('Delivery Update Error: ' . $e->getMessage());
            flash('danger', $e->getMessage());
        }

        redirect('orders.php' . ($filter !== 'all' ? '?filter=' . urlencode($filter) : ''));
    }
}

$pageTitle = 'Order Management';
include 'partials/header.php';
?>

<div class="card p-4">
    <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
        <h5 class="m-0">Order Management</h5>
        <!-- Status Filter Tabs -->
        <div class="btn-group btn-group-sm">
            <a href="orders.php?filter=all" class="btn btn-<?= $filter === 'all' ? 'primary' : 'outline-primary' ?>">All</a>
            <a href="orders.php?filter=pending" class="btn btn-<?= $filter === 'pending' ? 'warning' : 'outline-warning' ?>">Pending</a>
            <a href="orders.php?filter=partially_delivered" class="btn btn-<?= $filter === 'partially_delivered' ? 'info' : 'outline-info' ?>">Partially Delivered</a>
            <a href="orders.php?filter=delivered" class="btn btn-<?= $filter === 'delivered' ? 'success' : 'outline-success' ?>">Delivered</a>
        </div>
    </div>

    <div class="table-responsive">
        <table class="table align-middle">
            <thead>
                <tr>
                    <th>Order ID</th>
                    <th>Customer</th>
                    <th>Date</th>
                    <th>Total Price</th>
                    <th>Status</th>
                    <th>Delivery Note</th>
                    <th class="text-end">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                if ($filter !== 'all') {
                    $s = db()->prepare("SELECT o.*, u.full_name, u.phone, u.email, u.address FROM orders o LEFT JOIN users u ON o.user_id = u.id WHERE o.status = ? ORDER BY o.id DESC");
                    $s->bind_param("s", $filter);
                    $s->execute();
                    $r = $s->get_result();
                } else {
                    $r = db()->query("SELECT o.*, u.full_name, u.phone, u.email, u.address FROM orders o LEFT JOIN users u ON o.user_id = u.id ORDER BY o.id DESC");
                }
                
                if ($r->num_rows === 0): ?>
                    <tr>
                        <td colspan="7" class="text-center text-muted py-4">No orders found for this status.</td>
                    </tr>
                <?php endif;

                while ($o = $r->fetch_assoc()): 
                    $badgeClass = match($o['status']) {
                        'delivered'           => 'bg-success',
                        'partially_delivered' => 'bg-info text-dark',
                        'cancelled'           => 'bg-danger',
                        default               => 'bg-warning text-dark'
                    };
                    $statusLabel = ucwords(str_replace('_', ' ', $o['status']));

                    // Fetch items joined with products, display_types, and brands
                    $itemsStmt = db()->prepare("
                        SELECT 
                            oi.*, 
                            p.display_model AS product_display_model,
                            p.quantity AS stock_quantity,
                            dt.name AS display_quality,
                            b.name AS phone_brand_name
                        FROM order_items oi
                        LEFT JOIN products p ON oi.product_id = p.id
                        LEFT JOIN display_types dt ON oi.display_type_id = dt.id
                        LEFT JOIN brands b ON oi.phone_brand_id = b.id
                        WHERE oi.order_id = ?
                    ");
                    $itemsStmt->bind_param("i", $o['id']);
                    $itemsStmt->execute();
                    $items = $itemsStmt->get_result()->fetch_all(MYSQLI_ASSOC);
                ?>
                    <!-- Summary Row -->
                    <tr>
                        <td><strong>#<?=$o['id']?></strong></td>
                        <td>
                            <strong><?=e($o['full_name'] ?? 'Guest Customer')?></strong><br>
                            <small class="text-muted"><?=e($o['phone'] ?? '')?></small>
                        </td>
                        <td><small><?=date('M d, Y h:i A', strtotime($o['created_at']))?></small></td>
                        <td><strong>LKR <?=number_format($o['total_amount'], 2)?></strong></td>
                        <td>
                            <span class="badge <?=$badgeClass?>"><?=e($statusLabel)?></span>
                        </td>
                        <td>
                            <?php if (!empty($o['admin_comment'])): ?>
                                <small class="text-secondary"><?=nl2br(e($o['admin_comment']))?></small>
                            <?php else: ?>
                                <small class="text-muted"><em>No notes</em></small>
                            <?php endif; ?>
                        </td>
                        <td class="text-end">
                            <button class="btn btn-sm btn-primary" 
                                    type="button" 
                                    data-bs-toggle="collapse" 
                                    data-bs-target="#orderDetails<?=$o['id']?>" 
                                    aria-expanded="false">
                                View / Manage Items (<?=count($items)?>)
                            </button>
                        </td>
                    </tr>

                    <!-- Collapsible Delivery & Items Form Row -->
                    <tr class="p-0">
                        <td colspan="7" class="p-0 border-0">
                            <div class="collapse bg-light p-4 border-bottom" id="orderDetails<?=$o['id']?>">
                                <form method="post" action="orders.php?filter=<?=e($filter)?>">
                                    <input type="hidden" name="csrf" value="<?=e(csrf())?>">
                                    <input type="hidden" name="op" value="update_delivery">
                                    <input type="hidden" name="order_id" value="<?=$o['id']?>">

                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <h6 class="text-primary mb-1">Customer & Delivery Info</h6>
                                            <small class="d-block"><strong>Name:</strong> <?=e($o['full_name'] ?? 'N/A')?></small>
                                            <small class="d-block"><strong>Email:</strong> <?=e($o['email'] ?? 'N/A')?></small>
                                            <small class="d-block"><strong>Phone:</strong> <?=e($o['phone'] ?? 'N/A')?></small>
                                            <small class="d-block"><strong>Address:</strong> <?=nl2br(e($o['address'] ?? 'No address'))?></small>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-2">
                                                <label class="form-label font-weight-bold mb-1">Order Status</label>
                                                <select name="status" class="form-select form-select-sm" required>
                                                    <option value="pending" <?=$o['status']==='pending'?'selected':''?>>Pending</option>
                                                    <option value="partially_delivered" <?=$o['status']==='partially_delivered'?'selected':''?>>Partially Delivered</option>
                                                    <option value="delivered" <?=$o['status']==='delivered'?'selected':''?>>Delivered</option>
                                                    <option value="cancelled" <?=$o['status']==='cancelled'?'selected':''?>>Cancelled</option>
                                                </select>
                                            </div>
                                            <div>
                                                <label class="form-label mb-1">Delivery Comment / Notes</label>
                                                <input type="text" name="admin_comment" class="form-control form-control-sm" value="<?=e($o['admin_comment'] ?? '')?>" placeholder="e.g. Sent 2 units, balance next week...">
                                            </div>
                                        </div>
                                    </div>

                                    <h6 class="text-secondary mb-2">Item Delivery & Quality Breakdown</h6>
                                    <div class="table-responsive bg-white rounded border mb-3">
                                        <table class="table table-sm table-hover mb-0 align-middle">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Item / Model</th>
                                                    <th>Display Quality</th>
                                                    <th class="text-end">Unit Price</th>
                                                    <th class="text-center">Ordered Qty</th>
                                                    <th class="text-center">Current Stock</th>
                                                    <th class="text-center" style="width: 150px;">Delivered Qty</th>
                                                    <th class="text-end">Subtotal</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php 
                                                if (!empty($items)):
                                                    foreach ($items as $item): 
                                                        $deliveredQty = (int)($item['quantity_delivered'] ?? 0);
                                                        $itemName = $item['product_display_model'] ?? 'Display Item';
                                                        if (!empty($item['phone_brand_name']) || !empty($item['phone_model'])) {
                                                            $itemName .= ' (' . trim(($item['phone_brand_name'] ?? '') . ' ' . ($item['phone_model'] ?? '')) . ')';
                                                        }
                                                ?>
                                                        <tr>
                                                            <td><strong><?=e($itemName)?></strong></td>
                                                            <td>
                                                                <span class="badge bg-secondary"><?=e($item['display_quality'] ?? 'N/A')?></span>
                                                            </td>
                                                            <td class="text-end">LKR <?=number_format($item['unit_price'], 2)?></td>
                                                            <td class="text-center"><span class="badge bg-light text-dark border"><?=$item['quantity']?></span></td>
                                                            <td class="text-center"><span class="badge bg-primary"><?=isset($item['stock_quantity']) ? (int)$item['stock_quantity'] : 0?></span></td>
                                                            <td class="text-center">
                                                                <input type="number" 
                                                                       name="items[<?=$item['id']?>]" 
                                                                       class="form-control form-control-sm text-center" 
                                                                       min="0" 
                                                                       max="<?=$item['quantity']?>" 
                                                                       value="<?=$deliveredQty?>" 
                                                                       required>
                                                            </td>
                                                            <td class="text-end">LKR <?=number_format($item['subtotal'], 2)?></td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                    <tr class="fw-bold table-light">
                                                        <td colspan="6" class="text-end">Total Order Price:</td>
                                                        <td class="text-end text-success">LKR <?=number_format($o['total_amount'], 2)?></td>
                                                    </tr>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="7" class="text-center text-muted">No item records found.</td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>

                                    <div class="text-end">
                                        <button type="submit" class="btn btn-sm btn-success">
                                            Save Delivery Updates
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </td>
                    </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

<?php include 'partials/footer.php'; ?>