<?php
/**
 * Order History & Management Page
 * CMTC Shopping
 */
require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/navbar.php';

require_login();

$user_id = $_SESSION['user_id'];
$is_admin = has_permission($db, 'manage_orders');

$error = "";
$success = "";

// Handle status update by admin
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_order_status']) && $is_admin) {
    if (!validate_csrf_token($_POST['csrf_token'] ?? '')) {
        $error = "โทเค็นความปลอดภัยไม่ถูกต้อง";
    } else {
        $order_id = intval($_POST['order_id']);
        $new_status = $_POST['status'] ?? 'pending';

        try {
            $stmt_upd = $db->prepare("UPDATE orders SET status = ? WHERE id = ?");
            $stmt_upd->execute([$new_status, $order_id]);
            log_activity($db, 'edit', "อัปเดตสถานะคำสั่งซื้อ ID $order_id เป็น $new_status");
            $success = "อัปเดตสถานะคำสั่งซื้อเรียบร้อยแล้ว";
        } catch (Exception $e) {
            $error = "เกิดข้อผิดพลาด: " . $e->getMessage();
        }
    }
}

// Fetch orders
if ($is_admin) {
    $stmt = $db->query("
        SELECT o.*, u.username, u.firstname, u.lastname, u.phone,
               p.slip_path, p.payment_method
        FROM orders o
        JOIN users u ON o.user_id = u.id
        LEFT JOIN payments p ON o.id = p.order_id
        ORDER BY o.id DESC
    ");
    $orders = $stmt->fetchAll();
} else {
    $stmt = $db->prepare("
        SELECT o.*, u.username, u.firstname, u.lastname, u.phone,
               p.slip_path, p.payment_method
        FROM orders o
        JOIN users u ON o.user_id = u.id
        LEFT JOIN payments p ON o.id = p.order_id
        WHERE o.user_id = ?
        ORDER BY o.id DESC
    ");
    $stmt->execute([$user_id]);
    $orders = $stmt->fetchAll();
}
?>

<div class="d-flex">
    <?php if ($is_admin): ?>
        <?php require_once __DIR__ . '/../includes/sidebar.php'; ?>
    <?php endif; ?>

    <main class="flex-grow-1 p-4" style="background-color: var(--bs-body-bg);">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h3 class="fw-bold mb-0"><i class="bi bi-journal-text text-primary me-2"></i><?php echo $is_admin ? 'จัดการคำสั่งซื้อและรายการจอง' : 'ประวัติการสั่งซื้อและการจอง'; ?></h3>
                <p class="text-muted small mb-0">ตรวจสอบสถานะ ติดตามคำสั่งซื้อ และหลักฐานการชำระเงิน</p>
            </div>
            <div>
                <a href="<?php echo base_url('index.php'); ?>" class="btn btn-outline-primary btn-sm"><i class="bi bi-cart me-1"></i>ไปหน้าร้านค้า</a>
            </div>
        </div>

        <?php if (!empty($error)): ?>
            <div class="alert alert-danger mb-4"><?php echo $error; ?></div>
        <?php endif; ?>
        <?php if (!empty($success)): ?>
            <div class="alert alert-success mb-4"><?php echo $success; ?></div>
        <?php endif; ?>

        <div class="card border-0 shadow-sm glass-card p-4">
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead>
                        <tr>
                            <th>เลขที่คำสั่งซื้อ</th>
                            <?php if ($is_admin): ?>
                                <th>ลูกค้า</th>
                            <?php endif; ?>
                            <th>ยอดชำระ</th>
                            <th>หลักฐานสลิป</th>
                            <th>สถานะ</th>
                            <th>วันที่ทำรายการ</th>
                            <th class="text-center">จัดการ</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($orders) > 0): ?>
                            <?php foreach ($orders as $o): ?>
                                <tr>
                                    <td><code class="fw-bold fs-6"><?php echo sanitize($o['order_no']); ?></code></td>
                                    <?php if ($is_admin): ?>
                                        <td>
                                            <div class="fw-semibold"><?php echo sanitize($o['firstname'] . ' ' . $o['lastname']); ?></div>
                                            <small class="text-muted"><?php echo sanitize($o['phone']); ?></small>
                                        </td>
                                    <?php endif; ?>
                                    <td class="fw-bold text-primary"><?php echo format_price($o['net_amount']); ?></td>
                                    <td>
                                        <?php if (!empty($o['slip_path'])): ?>
                                            <a href="<?php echo base_url('uploads/slips/' . sanitize($o['slip_path'])); ?>" target="_blank" class="btn btn-sm btn-outline-info">
                                                <i class="bi bi-image me-1"></i> ดูสลิป
                                            </a>
                                        <?php else: ?>
                                            <span class="badge bg-secondary">ไม่มีสลิป</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php
                                        $badge_cls = 'bg-secondary';
                                        $st_name = $o['status'];
                                        if ($st_name === 'paid') { $badge_cls = 'bg-warning text-dark'; $st_name = 'แจ้งชำระแล้ว'; }
                                        elseif ($st_name === 'approved') { $badge_cls = 'bg-success'; $st_name = 'อนุมัติแล้ว'; }
                                        elseif ($st_name === 'preparing') { $badge_cls = 'bg-info text-dark'; $st_name = 'กำลังแพ็กของ'; }
                                        elseif ($st_name === 'ready') { $badge_cls = 'bg-primary'; $st_name = 'พร้อมรับสินค้า'; }
                                        elseif ($st_name === 'received') { $badge_cls = 'bg-dark'; $st_name = 'รับของแล้ว'; }
                                        elseif ($st_name === 'cancelled') { $badge_cls = 'bg-danger'; $st_name = 'ยกเลิกแล้ว'; }
                                        ?>
                                        <span class="badge <?php echo $badge_cls; ?>"><?php echo $st_name; ?></span>
                                    </td>
                                    <td><small class="text-muted"><?php echo format_thai_date($o['created_at'], true); ?></small></td>
                                    <td class="text-center">
                                        <a href="<?php echo base_url('views/order_detail.php?id=' . $o['id']); ?>" class="btn btn-sm btn-primary">
                                            <i class="bi bi-eye"></i> รายละเอียด
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="<?php echo $is_admin ? 7 : 6; ?>" class="text-center text-muted py-4">
                                    <i class="bi bi-inbox fs-2 d-block mb-1"></i>
                                    ยังไม่มีรายการคำสั่งซื้อหรือการจอง
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
