<?php
session_start();
require_once '../config.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);

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

/* =========================
   FLASH MESSAGE
========================= */
$flashType  = '';
$flashMsg   = '';

if (isset($_SESSION['flash'])) {
    $flashType = $_SESSION['flash']['type'] ?? '';
    $flashMsg  = $_SESSION['flash']['text'] ?? '';
    unset($_SESSION['flash']);
}

/* =========================
   APPROVE ORDER
   - add qty to products table
   - mark order approved
========================= */
if (isset($_POST['approve_order'])) {
    $id  = (int)($_POST['order_id'] ?? 0);
    $qty = (int)($_POST['qty'] ?? 0);

    if ($id <= 0 || $qty <= 0) {
        $_SESSION['flash'] = [
            'type' => 'error',
            'text' => 'Please enter a valid quantity.'
        ];
        header("Location: new_orders.php");
        exit;
    }

    try {
        $conn->begin_transaction();

        /* lock order row */
        $stmt = $conn->prepare("SELECT product_id, status FROM orders WHERE id = ? FOR UPDATE");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $orderRes = $stmt->get_result();
        $orderRow = $orderRes ? $orderRes->fetch_assoc() : null;
        $stmt->close();

        if (!$orderRow) {
            throw new Exception("Order not found.");
        }

        if (strtolower(trim($orderRow['status'] ?? '')) !== 'pending') {
            throw new Exception("This order has already been processed.");
        }

        $productId = (int)$orderRow['product_id'];

        /* increase product stock */
        $stmt = $conn->prepare("UPDATE products SET qty = qty + ? WHERE id = ?");
        $stmt->bind_param("ii", $qty, $productId);
        $stmt->execute();

        if ($stmt->affected_rows < 0) {
            $stmt->close();
            throw new Exception("Failed to update product stock.");
        }
        $stmt->close();

        /* update order */
        $stmt = $conn->prepare("UPDATE orders SET qty = ?, status = 'Approved' WHERE id = ?");
        $stmt->bind_param("ii", $qty, $id);
        $stmt->execute();
        $stmt->close();

        $conn->commit();

        $_SESSION['flash'] = [
            'type' => 'success',
            'text' => 'Order approved and product quantity updated successfully.'
        ];
    } catch (Throwable $e) {
        $conn->rollback();
        $_SESSION['flash'] = [
            'type' => 'error',
            'text' => $e->getMessage()
        ];
    }

    header("Location: new_orders.php");
    exit;
}

/* =========================
   REJECT ORDER
========================= */
if (isset($_POST['reject_order'])) {
    $id = (int)($_POST['order_id'] ?? 0);

    if ($id <= 0) {
        $_SESSION['flash'] = [
            'type' => 'error',
            'text' => 'Invalid order selected.'
        ];
        header("Location: new_orders.php");
        exit;
    }

    $stmt = $conn->prepare("UPDATE orders SET status = 'Rejected' WHERE id = ? AND status = 'Pending'");
    $stmt->bind_param("i", $id);
    $stmt->execute();

    if ($stmt->affected_rows > 0) {
        $_SESSION['flash'] = [
            'type' => 'success',
            'text' => 'Order rejected successfully.'
        ];
    } else {
        $_SESSION['flash'] = [
            'type' => 'error',
            'text' => 'Order not found or already processed.'
        ];
    }
    $stmt->close();

    header("Location: new_orders.php");
    exit;
}

/* =========================
   DASHBOARD COUNTS
========================= */
$totalOrders = 0;
$pendingOrders = 0;
$approvedOrders = 0;
$rejectedOrders = 0;

$res = $conn->query("SELECT COUNT(*) AS c FROM orders");
if ($res) $totalOrders = (int)($res->fetch_assoc()['c'] ?? 0);

$res = $conn->query("SELECT COUNT(*) AS c FROM orders WHERE status='Pending'");
if ($res) $pendingOrders = (int)($res->fetch_assoc()['c'] ?? 0);

$res = $conn->query("SELECT COUNT(*) AS c FROM orders WHERE status='Approved'");
if ($res) $approvedOrders = (int)($res->fetch_assoc()['c'] ?? 0);

$res = $conn->query("SELECT COUNT(*) AS c FROM orders WHERE status='Rejected'");
if ($res) $rejectedOrders = (int)($res->fetch_assoc()['c'] ?? 0);

/* =========================
   FETCH ORDERS
========================= */
$orders = [];

$query = "
SELECT
    o.id,
    o.qty,
    o.notes,
    o.status,
    o.created_at,
    p.product_name,
    mr.name AS mr_name,
    mgr.name AS manager_name,
    ag.name AS agency_name,
    COALESCE(mr.country, mgr.country, ag.country) AS country
FROM orders o
LEFT JOIN products p
    ON p.id = o.product_id
LEFT JOIN users mr
    ON mr.id = o.mr_id
LEFT JOIN users mgr
    ON mgr.id = mr.manager_id
LEFT JOIN users ag
    ON ag.id = mgr.agency_id
ORDER BY o.id DESC
";

$result = mysqli_query($conn, $query);

if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        $orders[] = $row;
    }
}

/* =========================
   HELPERS
========================= */
function e($v) {
    return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8');
}

function badge($status) {
    $status = strtolower(trim($status ?? ''));
    if ($status === 'approved') return 'approved';
    if ($status === 'rejected') return 'rejected';
    return 'pending';
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>New Orders</title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">

<style>

:root{
    --sidebar-width:260px;

    --bg:#f3f6fb;
    --card:#ffffff;

    --text:#0f172a;
    --muted:#64748b;

    --primary:#334155;
    --primary-dark:#1e293b;

    --success:#16a34a;
    --danger:#dc2626;
    --warning:#f59e0b;

    --border:#e2e8f0;

    --shadow:
        0 2px 12px rgba(15,23,42,.05);

    --radius:16px;
}

*{
    box-sizing:border-box;
}

body{
    margin:0;
    font-family:'Inter',sans-serif;
    background:#f1f5f9;
    color:var(--text);
}

/* PAGE */

.page{
    margin-left:var(--sidebar-width);
    padding:78px 14px 14px;
    min-height:100vh;
}

/* HERO */

.hero{
    background:#fff;
    border:1px solid var(--border);
    border-radius:18px;
    padding:16px 18px;
    margin-bottom:12px;
    box-shadow:var(--shadow);
}

.hero h1{
    margin:0;
    font-size:19px;
    font-weight:800;
    display:flex;
    align-items:center;
    gap:8px;
    color:#0f172a;
}

.hero h1 i{
    color:#334155;
}

.hero p{
    margin:5px 0 0;
    font-size:12px;
    color:#64748b;
    line-height:1.5;
}

/* FLASH */

.flash{
    margin-bottom:12px;
    padding:10px 12px;
    border-radius:12px;
    font-size:12px;
    font-weight:600;
    display:flex;
    align-items:center;
    gap:8px;
}

.flash.success{
    background:#ecfdf5;
    color:#166534;
    border:1px solid #bbf7d0;
}

.flash.error{
    background:#fef2f2;
    color:#991b1b;
    border:1px solid #fecaca;
}

/* STATS */

.stats{
    display:grid;
    grid-template-columns:repeat(4,1fr);
    gap:10px;
    margin-bottom:12px;
}

.stat-card{
    background:#fff;
    border:1px solid var(--border);
    border-radius:16px;
    padding:12px;
    box-shadow:var(--shadow);
}

.stat-card .label{
    font-size:10px;
    font-weight:700;
    color:#64748b;
    text-transform:uppercase;
    letter-spacing:.3px;
}

.stat-card .value{
    margin-top:4px;
    font-size:19px;
    font-weight:800;
}

.stat-card.total .value{
    color:#334155;
}

.stat-card.pending .value{
    color:#92400e;
}

.stat-card.approved .value{
    color:#166534;
}

.stat-card.rejected .value{
    color:#991b1b;
}

/* CARD */

.card{
    background:#fff;
    border:1px solid var(--border);
    border-radius:18px;
    overflow:hidden;
    box-shadow:var(--shadow);
}

/* TABLE TOP */

.table-top{
    padding:12px 16px;
    border-bottom:1px solid #eef2f7;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:10px;
    flex-wrap:wrap;
}

.table-top h2{
    margin:0;
    font-size:15px;
    font-weight:700;
    color:#0f172a;
}

.table-top .sub{
    font-size:11px;
    color:#64748b;
}

/* TABLE */

.table-wrap{
    overflow:auto;
    cursor:grab;
    user-select:none;
    scroll-behavior:smooth;
}

.table-wrap.active{
    cursor:grabbing;
}

table{
    width:100%;
    border-collapse:collapse;
    min-width:1120px;
}

thead{
    background:#334155;
}

th{
    padding:11px 12px;
    text-align:left;
    color:#fff;
    font-size:11px;
    font-weight:700;
    white-space:nowrap;
}

td{
    padding:11px 12px;
    border-bottom:1px solid #eef2f7;
    font-size:12px;
    color:#1e293b;
    white-space:nowrap;
    background:#fff;
    transition:.15s ease;
}

tbody tr:hover td{
    background:#f8fbff;
}

/* NOTES */

.note{
    max-width:170px;
    overflow:hidden;
    text-overflow:ellipsis;
    color:#64748b;
}

/* BADGES */

.badge{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    min-width:68px;
    padding:5px 8px;
    border-radius:999px;
    font-size:10px;
    font-weight:700;
}

.badge.pending{
    background:#fef3c7;
    color:#92400e;
}

.badge.approved{
    background:#dcfce7;
    color:#166534;
}

.badge.rejected{
    background:#fee2e2;
    color:#991b1b;
}

/* ACTION FORM */

.action-form{
    display:flex;
    align-items:center;
    gap:5px;
    flex-wrap:wrap;
}

/* INPUT */

.qty-input{
    width:58px;
    height:32px;
    border-radius:8px;
    border:1px solid #dbe4ee;
    background:#fff;
    text-align:center;
    font-size:11px;
    outline:none;
}

.qty-input:focus{
    border-color:#334155;
    box-shadow:0 0 0 3px rgba(51,65,85,.08);
}

/* BUTTONS */

.btn{
    height:32px;
    border:none;
    border-radius:8px;
    padding:0 10px;
    color:#fff;
    font-size:10px;
    font-weight:700;
    cursor:pointer;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:5px;
    transition:.15s ease;
}

.btn:hover{
    transform:translateY(-1px);
}

.btn-approve{
    background:#16a34a;
}

.btn-reject{
    background:#dc2626;
}

/* EMPTY */

.empty{
    text-align:center;
    padding:24px;
    color:#64748b;
    font-size:13px;
}

/* SCROLLBAR */

.table-wrap::-webkit-scrollbar{
    height:6px;
}

.table-wrap::-webkit-scrollbar-track{
    background:#e2e8f0;
}

.table-wrap::-webkit-scrollbar-thumb{
    background:#94a3b8;
    border-radius:20px;
}

/* MOBILE */

@media(max-width:992px){

    .page{
        margin-left:0;
        padding:80px 10px 10px;
    }

    .stats{
        grid-template-columns:1fr 1fr;
    }
}

@media(max-width:768px){

    .hero{
        padding:14px;
    }

    .hero h1{
        font-size:17px;
    }

    .hero p{
        font-size:11px;
    }

    .stats{
        grid-template-columns:1fr;
    }

    th,
    td{
        padding:10px;
        font-size:11px;
    }

    .btn{
        height:30px;
        font-size:10px;
    }
}

</style>
</head>
<body>

<?php include 'adminsidebar.php'; ?>
<?php include '../header.php'; ?>

<div class="page">

    <div class="hero">
        <h1><i class="fa-solid fa-cart-shopping"></i> New Orders</h1>
        <p>Approve pending medical representative orders and add quantity directly into product stock.</p>
    </div>

    <?php if ($flashMsg !== ''): ?>
        <div class="flash <?php echo e($flashType); ?>">
            <i class="fa-solid <?php echo $flashType === 'success' ? 'fa-circle-check' : 'fa-triangle-exclamation'; ?>"></i>
            <span><?php echo e($flashMsg); ?></span>
        </div>
    <?php endif; ?>

    <div class="stats">
        <div class="stat-card total">
            <div class="label">Total Orders</div>
            <div class="value"><?php echo (int)$totalOrders; ?></div>
        </div>
        <div class="stat-card pending">
            <div class="label">Pending</div>
            <div class="value"><?php echo (int)$pendingOrders; ?></div>
        </div>
        <div class="stat-card approved">
            <div class="label">Approved</div>
            <div class="value"><?php echo (int)$approvedOrders; ?></div>
        </div>
        <div class="stat-card rejected">
            <div class="label">Rejected</div>
            <div class="value"><?php echo (int)$rejectedOrders; ?></div>
        </div>
    </div>

    <div class="card">
        <div class="table-top">
            <h2>Order Requests</h2>
            <div class="sub">Edit quantity before approval. Approved qty is added to product stock.</div>
        </div>

        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>MR Name</th>
                        <th>Manager</th>
                        <th>Agency</th>
                        <th>Country</th>
                        <th>Product</th>
                        <th>Qty</th>
                        <th>Notes</th>
                        <th>Status</th>
                        <th>Date</th>
                        <th>Action</th>
                    </tr>
                </thead>

                <tbody>
                <?php if (!empty($orders)): ?>
                    <?php foreach ($orders as $row): ?>
                        <tr>
                            <td>#<?php echo (int)$row['id']; ?></td>
                            <td><?php echo e($row['mr_name']); ?></td>
                            <td><?php echo e($row['manager_name']); ?></td>
                            <td><?php echo e($row['agency_name']); ?></td>
                            <td><?php echo e($row['country']); ?></td>
                            <td><?php echo e($row['product_name']); ?></td>
                            <td><?php echo (int)$row['qty']; ?></td>
                            <td class="note" title="<?php echo e($row['notes']); ?>"><?php echo e($row['notes']); ?></td>
                            <td>
                                <span class="badge <?php echo badge($row['status']); ?>">
                                    <?php echo e($row['status']); ?>
                                </span>
                            </td>
                            <td><?php echo date("d M Y", strtotime($row['created_at'])); ?></td>
                            <td>
                                <?php if (strtolower(trim($row['status'] ?? '')) === 'pending'): ?>
                                    <form method="post" class="action-form">
                                        <input type="hidden" name="order_id" value="<?php echo (int)$row['id']; ?>">
                                        <input
                                            type="number"
                                            name="qty"
                                            class="qty-input"
                                            min="1"
                                            value="<?php echo (int)$row['qty']; ?>"
                                            required
                                            title="Final approved quantity"
                                        >
                                        <button type="submit" name="approve_order" class="btn btn-approve">
                                            <i class="fa-solid fa-check"></i> Approve
                                        </button>
                                        <button type="submit" name="reject_order" class="btn btn-reject" onclick="return confirm('Reject this order?');">
                                            <i class="fa-solid fa-xmark"></i> Reject
                                        </button>
                                    </form>
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="11" class="empty">No order requests found.</td>
                    </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<script>

/* =========================
   DRAG TO SCROLL TABLE
========================= */

const slider = document.querySelector('.table-wrap');

let isDown = false;
let startX;
let scrollLeft;

slider.addEventListener('mousedown', (e) => {

    isDown = true;

    slider.classList.add('active');

    startX = e.pageX - slider.offsetLeft;

    scrollLeft = slider.scrollLeft;
});

slider.addEventListener('mouseleave', () => {

    isDown = false;

    slider.classList.remove('active');
});

slider.addEventListener('mouseup', () => {

    isDown = false;

    slider.classList.remove('active');
});

slider.addEventListener('mousemove', (e) => {

    if(!isDown) return;

    e.preventDefault();

    const x = e.pageX - slider.offsetLeft;

    const walk = (x - startX) * 2;

    slider.scrollLeft = scrollLeft - walk;
});

</script>
</body>
</html>