<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once("../php/db_connect.php");

if (!isset($_SESSION["user_id"])) {
    echo "<script>window.location='index.php';</script>";
    exit();
}

$customer_id = (int)$_SESSION["user_id"];
$customer_email = $_SESSION["email"] ?? "";
$search = trim($_GET["search"] ?? "");

function h($value) {
    return htmlspecialchars($value ?? "", ENT_QUOTES, "UTF-8");
}

function formatDateOnly($date) {
    if (empty($date) || $date === "0000-00-00") {
        return "N/A";
    }

    return date("M d, Y", strtotime($date));
}

function formatStatusText($status) {
    return ucwords(str_replace("_", " ", $status ?: "pending"));
}

function statusBadgeClass($status) {
    $status = strtolower($status ?? "");

    if ($status === "pending") return "bg-warning-subtle text-warning-emphasis border border-warning-subtle";
    if ($status === "accepted") return "bg-info-subtle text-info border border-info-subtle";
    if ($status === "in_progress") return "bg-primary-subtle text-primary border border-primary-subtle";
    if ($status === "outsourced") return "bg-secondary-subtle text-secondary border border-secondary-subtle";
    if ($status === "completed") return "bg-success-subtle text-success border border-success-subtle";
    if ($status === "cancelled") return "bg-danger-subtle text-danger border border-danger-subtle";

    return "bg-light text-dark border";
}

function progressPercent($status) {
    $status = strtolower($status ?? "");

    if ($status === "pending") return 20;
    if ($status === "accepted") return 40;
    if ($status === "in_progress") return 65;
    if ($status === "outsourced") return 70;
    if ($status === "completed") return 100;
    if ($status === "cancelled") return 0;

    return 10;
}

/*
|--------------------------------------------------------------------------
| LOAD CUSTOMER ORDERS
|--------------------------------------------------------------------------
*/
$sql = "
    SELECT 
        o.*,
        s.shop_name,

        j.status AS outsourced_status,
        j.notes AS outsourced_notes,
        j.updated_at AS outsourced_updated_at,

        executor.shop_name AS executor_shop_name
    FROM orders o
    LEFT JOIN users s 
        ON o.shop_id = s.id

    LEFT JOIN outsourced_jobs j
        ON j.order_id = o.id

    LEFT JOIN users executor
        ON j.executor_shop_id = executor.id

    WHERE 
        (
            o.customer_id = ?
            OR o.customer_email = ?
        )
";

$params = [$customer_id, $customer_email];
$types = "is";

if ($search !== "") {
    $sql .= " AND o.order_code LIKE ? ";
    $searchLike = "%" . $search . "%";
    $params[] = $searchLike;
    $types .= "s";
}

$sql .= " ORDER BY o.created_at DESC";

$stmt = $conn->prepare($sql);

if (!$stmt) {
    die("Prepare failed: " . $conn->error);
}

$stmt->bind_param($types, ...$params);
$stmt->execute();
$orders = $stmt->get_result();
?>

<div class="container-fluid px-0 track-order-page">

    <div class="d-flex justify-content-between align-items-center flex-wrap gap-3 mb-4">
        <div>
            <h1 class="fw-bold mb-1">Track Order</h1>
            <p class="text-muted mb-0">
                Monitor the current status of your orders.
            </p>
        </div>
    </div>

    <div class="card border-0 shadow-sm rounded-4 mb-4">
        <div class="card-body p-4">
            <form method="GET" class="row g-3 align-items-end">
                <input type="hidden" name="page" value="track-order">

                <div class="col-md-8">
                    <label class="form-label fw-semibold">Search Order Code</label>
                    <input 
                        type="text" 
                        name="search" 
                        class="form-control" 
                        placeholder="Example: ORD-123456"
                        value="<?php echo h($search); ?>"
                    >
                </div>

                <div class="col-md-4 d-flex gap-2">
                    <button type="submit" class="btn btn-primary px-4">
                        Search
                    </button>

                    <a href="customer.php?page=track-order" class="btn btn-light border px-4">
                        Reset
                    </a>
                </div>
            </form>
        </div>
    </div>

    <div class="row g-4">

        <?php if ($orders && $orders->num_rows > 0): ?>
            <?php while ($order = $orders->fetch_assoc()): ?>

                <?php
                $mainStatus = strtolower($order["status"] ?? "pending");
                $displayStatus = $mainStatus;

                if ($mainStatus === "outsourced" && !empty($order["outsourced_status"])) {
                    $displayStatus = $order["outsourced_status"];
                }

                $progress = progressPercent($displayStatus);
                ?>

                <div class="col-12">
                    <div class="card border-0 shadow-sm rounded-4 order-card">
                        <div class="card-body p-4">

                            <div class="d-flex justify-content-between align-items-start flex-wrap gap-3 mb-3">
                                <div>
                                    <h4 class="fw-bold mb-1">
                                        <?php echo h($order["order_code"]); ?>
                                    </h4>

                                    <p class="text-muted mb-0">
                                        Shop:
                                        <strong><?php echo h($order["shop_name"] ?: "N/A"); ?></strong>
                                    </p>
                                </div>

                                <span class="badge rounded-pill px-3 py-2 <?php echo statusBadgeClass($displayStatus); ?>">
                                    <?php echo h(formatStatusText($displayStatus)); ?>
                                </span>
                            </div>

                            <div class="row g-3 mb-4">

                                <div class="col-md-3">
                                    <div class="info-box">
                                        <small>Service</small>
                                        <strong><?php echo h($order["service_type"] ?: "N/A"); ?></strong>
                                    </div>
                                </div>

                                <div class="col-md-3">
                                    <div class="info-box">
                                        <small>Item</small>
                                        <strong><?php echo h($order["item_name"] ?: "N/A"); ?></strong>
                                    </div>
                                </div>

                                <div class="col-md-2">
                                    <div class="info-box">
                                        <small>Quantity</small>
                                        <strong><?php echo (int)($order["quantity"] ?? 0); ?></strong>
                                    </div>
                                </div>

                                <div class="col-md-2">
                                    <div class="info-box">
                                        <small>Size</small>
                                        <strong><?php echo h($order["size"] ?: "N/A"); ?></strong>
                                    </div>
                                </div>

                                <div class="col-md-2">
                                    <div class="info-box">
                                        <small>Due Date</small>
                                        <strong><?php echo h(formatDateOnly($order["due_date"])); ?></strong>
                                    </div>
                                </div>

                            </div>

                            <div class="progress-box mb-4">
                                <div class="d-flex justify-content-between mb-2">
                                    <span class="fw-semibold">Order Progress</span>
                                    <span class="text-muted"><?php echo (int)$progress; ?>%</span>
                                </div>

                                <div class="progress">
                                    <div 
                                        class="progress-bar"
                                        role="progressbar"
                                        style="width: <?php echo (int)$progress; ?>%;"
                                        aria-valuenow="<?php echo (int)$progress; ?>"
                                        aria-valuemin="0"
                                        aria-valuemax="100">
                                    </div>
                                </div>

                                <div class="tracking-steps mt-3">
                                    <span class="<?php echo $progress >= 20 ? 'active' : ''; ?>">Pending</span>
                                    <span class="<?php echo $progress >= 40 ? 'active' : ''; ?>">Accepted</span>
                                    <span class="<?php echo $progress >= 65 ? 'active' : ''; ?>">In Progress</span>
                                    <span class="<?php echo $progress >= 100 ? 'active' : ''; ?>">Completed</span>
                                </div>
                            </div>

                            <?php if ($mainStatus === "outsourced"): ?>
                                <div class="outsourced-note mb-3">
                                    <div>
                                        <strong>Outsourced Job Update</strong>
                                        <p class="mb-1">
                                            Partner Shop:
                                            <?php echo h($order["executor_shop_name"] ?: "N/A"); ?>
                                        </p>

                                        <p class="mb-1">
                                            Status:
                                            <?php echo h(formatStatusText($order["outsourced_status"] ?: "assigned")); ?>
                                        </p>

                                        <p class="mb-0">
                                            Note:
                                            <?php echo !empty($order["outsourced_notes"]) ? h($order["outsourced_notes"]) : "No update note yet."; ?>
                                        </p>
                                    </div>
                                </div>
                            <?php endif; ?>

                            <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">

    <div class="text-muted small">
        Payment Status:
        <strong><?php echo h(ucfirst($order["payment_status"] ?: "N/A")); ?></strong>
    </div>

    <div class="d-flex gap-2">

        <!-- MESSAGE SHOP -->
        <a 
            href="customer.php?page=messages&receiver_id=<?php echo (int)$order["shop_id"]; ?>&order_id=<?php echo (int)$order["id"]; ?>"
            class="btn btn-outline-primary btn-sm"
        >
            <i class="fa-solid fa-message me-1"></i> Message Shop
        </a>

        <!-- CANCEL ORDER -->
        <?php if (strtolower($order["status"]) === "pending"): ?>

            <a 
                href="../php/cancel-order.php?order_id=<?php echo (int)$order["id"]; ?>"
                class="btn btn-danger btn-sm"
                onclick="return confirm('Are you sure you want to cancel this order?');"
            >
                <i class="fa-solid fa-xmark me-1"></i>
                Cancel Order
            </a>

        <?php endif; ?>

    </div>

</div>

                        </div>
                    </div>
                </div>

            <?php endwhile; ?>

        <?php else: ?>

            <div class="col-12">
                <div class="card border-0 shadow-sm rounded-4">
                    <div class="card-body">
                        <div class="empty-state">
                            <i class="fa-solid fa-box-open"></i>
                            <h5 class="fw-bold mb-1">No orders found</h5>
                            <p class="text-muted mb-0">
                                Your orders will appear here once you place an order.
                            </p>
                        </div>
                    </div>
                </div>
            </div>

        <?php endif; ?>

    </div>

</div>

<style>
.track-order-page {
    width: 100%;
}

.track-order-page h1 {
    font-size: clamp(26px, 2.2vw, 38px);
    color: #111827;
}

.form-control {
    border-radius: 12px;
    padding: 10px 12px;
}

.order-card {
    overflow: hidden;
}

.info-box {
    background: #f8fafc;
    border: 1px solid #eef2f7;
    border-radius: 16px;
    padding: 16px;
    height: 100%;
}

.info-box small {
    display: block;
    color: #6b7280;
    margin-bottom: 6px;
    font-size: 13px;
}

.info-box strong {
    color: #111827;
    font-size: 15px;
}

.progress-box {
    background: #f8fafc;
    border: 1px solid #eef2f7;
    border-radius: 18px;
    padding: 18px;
}

.progress {
    height: 12px;
    border-radius: 999px;
    background: #e5e7eb;
}

.progress-bar {
    background: #0ea5e9;
    border-radius: 999px;
}

.tracking-steps {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 8px;
    font-size: 13px;
    color: #9ca3af;
    text-align: center;
}

.tracking-steps span {
    background: #fff;
    border: 1px solid #e5e7eb;
    padding: 8px;
    border-radius: 999px;
}

.tracking-steps span.active {
    color: #0369a1;
    background: #e0f2fe;
    border-color: #bae6fd;
    font-weight: 700;
}

.outsourced-note {
    background: #f8fafc;
    border-left: 4px solid #0ea5e9;
    border-radius: 14px;
    padding: 14px 16px;
}

.empty-state {
    padding: 50px 20px;
    text-align: center;
    color: #6b7280;
}

.empty-state i {
    font-size: 40px;
    color: #9ca3af;
    margin-bottom: 12px;
}

@media (max-width: 768px) {
    .tracking-steps {
        grid-template-columns: 1fr 1fr;
    }
}
</style>