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

include "../db.php";

/* ---------- HANDLE AJAX ---------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax'])) {
    header('Content-Type: application/json');

    $action = $_POST['action'] ?? '';

    /* UPDATE ORDER */
    if ($action === 'update_order') {
        $order_id = (int)($_POST['order_id'] ?? 0);
        $awb_number = trim($_POST['awb_number'] ?? '');
        $order_status = trim($_POST['order_status'] ?? '');

        if ($order_id <= 0 || $order_status === '') {
            echo json_encode(['success' => false, 'message' => 'Invalid data']);
            exit;
        }

        $stmt = $pdo->prepare("
            UPDATE orders 
            SET awb_number = ?, order_status = ?
            WHERE id = ?
        ");
        $stmt->execute([$awb_number, $order_status, $order_id]);

        echo json_encode(['success' => true]);
        exit;
    }

    /* GET ORDER ITEMS (WITH VARIANTS) */
    if ($action === 'get_items') {
        $order_id = (int)($_POST['order_id'] ?? 0);

        if ($order_id <= 0) {
            echo json_encode(['success' => false, 'message' => 'Invalid Order']);
            exit;
        }

        $stmt = $pdo->prepare("
            SELECT 
                oi.id,
                p.product_name,
                oi.variant_details,
                oi.qty,
                oi.price,
                oi.created_at
            FROM order_items oi
            LEFT JOIN products p ON oi.product_id = p.id
            WHERE oi.order_id = ?
            ORDER BY oi.id ASC
        ");
        $stmt->execute([$order_id]);
        $items = $stmt->fetchAll(PDO::FETCH_ASSOC);

        echo json_encode(['success' => true, 'items' => $items]);
        exit;
    }

    echo json_encode(['success' => false, 'message' => 'Unknown action']);
    exit;
}

/* ---------- FETCH ORDERS ---------- */
$orders = $pdo->query("SELECT * FROM orders ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
$order_statuses = ['pending','processing','shipped','delivered','cancelled'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Manage Orders</title>
<meta name="viewport" content="width=device-width,initial-scale=1">

<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
:root{
    --primary:#0b4f27;
    --primary-dark:#083a1d;
    --bg:#f3f4f6;
}

body{font-family:'Poppins',sans-serif;background:var(--bg);}
.page-wrapper{padding:20px;}

.card{
    border-radius:14px;
    border:none;
    box-shadow:0 8px 20px rgba(0,0,0,.06);
}

.page-title{color:var(--primary);font-weight:600;}

.status-badge{
    padding:4px 10px;
    border-radius:30px;
    font-size:12px;
}

.status-pending{background:#fef3c7;color:#92400e;}
.status-processing{background:#e0f2fe;color:#075985;}
.status-shipped{background:#dcfce7;color:#166534;}
.status-delivered{background:#bbf7d0;color:#065f46;}
.status-cancelled{background:#fee2e2;color:#7f1d1d;}

.btn-save{
    background:var(--primary);
    color:#fff;
}
.btn-save:hover{background:var(--primary-dark);}

.modal-content{border-radius:14px;}
</style>
</head>

<body>

<div class="page-wrapper">

<div class="d-flex justify-content-between align-items-center mb-3">
    <div>
        <h3 class="page-title mb-0">Manage Orders</h3>
        <small class="text-muted">View variants, update status & AWB</small>
    </div>

    <div class="input-group" style="max-width:350px;">
        <input type="text" id="searchInput" class="form-control form-control-sm" placeholder="Search order / name / phone">
        <button class="btn btn-outline-secondary btn-sm" id="clearSearch">Clear</button>
    </div>
</div>

<div class="card">
<div class="table-responsive">
<table class="table table-hover mb-0" id="ordersTable">
<thead class="table-light">
<tr>
    <th>Order</th>
    <th>Customer</th>
    <th>Phone</th>
    <th>Total</th>
    <th>Status</th>
    <th>AWB</th>
    <th>Created</th>
    <th>Items</th>
    <th>Save</th>
</tr>
</thead>
<tbody>

<?php foreach($orders as $o):
$full = trim(($o['first_name']??'').' '.($o['last_name']??''));
$status = $o['order_status'] ?? 'pending';
?>
<tr data-order-id="<?= $o['id'] ?>">
<td>#<?= $o['id'] ?></td>
<td><?= htmlspecialchars($full ?: 'N/A') ?></td>
<td><?= htmlspecialchars($o['phone']) ?></td>
<td>₹<?= number_format($o['total_amount'],2) ?></td>

<td>
<span class="status-badge status-<?= $status ?>"><?= ucfirst($status) ?></span>
<select class="form-select form-select-sm mt-1 order-status-select">
<?php foreach($order_statuses as $st): ?>
<option value="<?= $st ?>" <?= $st==$status?'selected':'' ?>><?= ucfirst($st) ?></option>
<?php endforeach; ?>
</select>
</td>

<td><input type="text" class="form-control form-control-sm awb-input" value="<?= htmlspecialchars($o['awb_number']) ?>"></td>
<td><?= $o['created_at'] ?></td>

<td><button class="btn btn-sm btn-outline-primary view-items-btn">View</button></td>
<td><button class="btn btn-sm btn-save">Save</button></td>
</tr>
<?php endforeach; ?>

</tbody>
</table>
</div>
</div>
</div>

<!-- MODAL -->
<div class="modal fade" id="itemsModal" tabindex="-1">
<div class="modal-dialog modal-lg modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Order Items</h5>
<button class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body" id="itemsContent">Loading...</div>
</div>
</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

<script>
(function(){

const table=document.getElementById("ordersTable");
const search=document.getElementById("searchInput");
const clearBtn=document.getElementById("clearSearch");
const modal=new bootstrap.Modal(document.getElementById("itemsModal"));
const modalBody=document.getElementById("itemsContent");

function saveOrder(row){
    let fd=new FormData();
    fd.append("ajax","1");
    fd.append("action","update_order");
    fd.append("order_id",row.dataset.orderId);
    fd.append("awb_number",row.querySelector(".awb-input").value);
    fd.append("order_status",row.querySelector(".order-status-select").value);

    fetch("",{method:"POST",body:fd});
}

function viewItems(row){
    modalBody.innerHTML="Loading...";
    modal.show();

    let fd=new FormData();
    fd.append("ajax","1");
    fd.append("action","get_items");
    fd.append("order_id",row.dataset.orderId);

    fetch("",{method:"POST",body:fd})
    .then(r=>r.json())
    .then(d=>{
        if(!d.success || !d.items.length){
            modalBody.innerHTML="<p>No items found</p>";
            return;
        }

        let html=`<div class="table-responsive">
        <table class="table table-sm table-striped">
        <thead>
        <tr>
            <th>ID</th>
            <th>Product</th>
            <th>Variant</th>
            <th>Qty</th>
            <th>Price</th>
            <th>Date</th>
        </tr>
        </thead><tbody>`;

        d.items.forEach(i=>{
            html+=`<tr>
            <td>${i.id}</td>
            <td>${i.product_name}</td>
            <td>${i.variant_details || 'N/A'}</td>
            <td>${i.qty}</td>
            <td>₹${parseFloat(i.price).toFixed(2)}</td>
            <td>${i.created_at}</td>
            </tr>`;
        });

        html+=`</tbody></table></div>`;
        modalBody.innerHTML=html;
    });
}

table.addEventListener("click",e=>{
    let row=e.target.closest("tr");
    if(!row) return;
    if(e.target.classList.contains("btn-save")) saveOrder(row);
    if(e.target.classList.contains("view-items-btn")) viewItems(row);
});

search.addEventListener("input",()=>{
    let q=search.value.toLowerCase();
    table.querySelectorAll("tbody tr").forEach(r=>{
        r.style.display=r.innerText.toLowerCase().includes(q)?"":"none";
    });
});

clearBtn.onclick=()=>{
    search.value="";
    search.dispatchEvent(new Event("input"));
};

})();
</script>

</body>
</html>
