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

require_once "../php/db_connect.php";

$ordersData = [];
$inProgressCount = 0;
$completedCount = 0;
$totalOrders = 0;


$customer_id = $_SESSION["user_id"];
$customer_email = $_SESSION["email"] ?? '';
$customer_mobile = $_SESSION["contact_number"] ?? '';

$sql = "
    SELECT 
        o.*,
        GROUP_CONCAT(
            CONCAT(
                COALESCE(oi.service_type, ''),
                CASE 
                    WHEN oi.sub_type IS NOT NULL AND oi.sub_type != '' 
                    THEN CONCAT(' (', oi.sub_type, ')')
                    ELSE ''
                END
            )
            SEPARATOR ', '
        ) AS all_task_names,
        SUM(COALESCE(oi.quantity, 0)) AS total_item_qty
    FROM orders o
    LEFT JOIN order_items oi ON oi.order_id = o.id
    WHERE 
        o.customer_id = ?
        OR (o.customer_id IS NULL AND o.customer_email = ?)
        OR (o.customer_id IS NULL AND o.customer_mobile = ?)
    GROUP BY o.id
    ORDER BY o.id DESC
";

$stmt = $conn->prepare($sql);
$stmt->bind_param("iss", $customer_id, $customer_email, $customer_mobile);

$stmt->execute();
$result = $stmt->get_result();

if ($result) {
    while ($row = $result->fetch_assoc()) {
        $ordersData[] = $row;
        $totalOrders++;

        if (($row["status"] ?? "") === "in_progress") {
            $inProgressCount++;
        }

        if (($row["status"] ?? "") === "completed") {
            $completedCount++;
        }
    }
} else {
    die("Query failed: " . $conn->error);
}
?>

<div class="customer-dashboard">
    <div class="card border-0 shadow-sm rounded-4 mb-4 dashboard-card">
        <div class="card-body p-4 d-flex flex-column flex-lg-row justify-content-between align-items-lg-center gap-4">
            <div class="welcome-text">
                <h2 class="fw-bold mb-2">Hello <?php echo htmlspecialchars($_SESSION["first_name"]); ?>!</h2>
                <p class="mb-3 text-secondary">Your recent order is being processed.</p>
                <a href="#" class="link-info">View</a>
            </div>

            <div class="welcome-image text-center">
                <img src="images/welcome-girl.png" alt="Welcome Illustration" class="img-fluid welcome-illustration">
            </div>
        </div>
    </div>

    <div class="card border-0 shadow-sm rounded-4 dashboard-card">
        <div class="card-body p-4">
            <h2 class="fw-bold mb-1">Your Order Status</h2>
            <p class="subtitle text-secondary mb-3">Status Overview</p>

            <?php if (count($ordersData) > 0): ?>
                <div class="table-responsive">
                    <table class="table align-middle customer-orders-table">
                        <thead class="table-light">
                            <tr>
                                <th>Order ID</th>
                                <th>Task Name</th>
                                <th>Quantity</th>
                                <th>Status</th>
                                <th>Est. Delivery</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($ordersData as $row): ?>
                                <?php
                                    $status = $row["status"] ?? "pending";
                                    $statusClass = "status-pending";

                                    if ($status === "in_progress") {
                                        $statusClass = "status-progress";
                                    } elseif ($status === "completed") {
                                        $statusClass = "status-completed";
                                    } elseif ($status === "cancelled") {
                                        $statusClass = "status-cancelled";
                                    }

                                    $taskName = trim($row["all_task_names"] ?? '') !== '' 
    ? $row["all_task_names"] 
    : 'N/A';

$qty = (int)($row["total_item_qty"] ?? $row["quantity"] ?? 0);
                                ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($row["order_code"] ?? "N/A"); ?></td>
                                    <td><?php echo htmlspecialchars($taskName); ?></td>
                                    <td><?php echo htmlspecialchars((string)$qty); ?></td>
                                    <td>
                                        <span class="status-badge <?php echo $statusClass; ?>">
                                            <?php echo htmlspecialchars(ucwords(str_replace("_", " ", $status))); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php
                                            $delivery = trim($row["estimated_delivery"] ?? '');
                                            $dueDate = trim($row["due_date"] ?? '');

                                            if ($delivery !== '' && $delivery !== '0000-00-00') {
                                                echo htmlspecialchars(date("M j, Y", strtotime($delivery)));
                                            } elseif ($dueDate !== '' && $dueDate !== '0000-00-00') {
                                                echo htmlspecialchars(date("M j, Y", strtotime($dueDate)));
                                            } else {
                                                echo "N/A";
                                            }
                                        ?>
                                    </td>
                                    <td>
                                        <a href="customer.php?page=customer-order-details&order_id=<?php echo (int)($row["id"] ?? 0); ?>" class="btn btn-info btn-sm text-white rounded-3">
                                            View Details
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <div class="orders-summary mt-3">
                    Order progress <?php echo $inProgressCount; ?> |
                    Past orders (<?php echo $completedCount; ?>)
                </div>
            <?php else: ?>
                <p class="no-orders mb-0">No orders found.</p>
            <?php endif; ?>
        </div>
    </div>
</div>