<?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();
}

$current_user_id = (int)$_SESSION["user_id"];

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 formatDateTime($date) {
    if (empty($date)) {
        return "N/A";
    }

    return date("M d, Y h:i A", strtotime($date));
}

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

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

    if ($status === "assigned") {
        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 === "ready_for_pickup") {
        return "bg-warning-subtle text-warning-emphasis border border-warning-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-secondary-subtle text-secondary border border-secondary-subtle";
}

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

    if ($status === "assigned") return 25;
    if ($status === "in_progress") return 50;
    if ($status === "ready_for_pickup") return 75;
    if ($status === "completed") return 100;
    if ($status === "cancelled") return 0;

    return 10;
}

/*
|--------------------------------------------------------------------------
| LOAD JOB TRACKING DATA
| Original shop can monitor outsourced jobs.
| Executor shop can also see assigned jobs, but status update remains in Outsourced Jobs.
|--------------------------------------------------------------------------
*/
$stmt = $conn->prepare("
    SELECT 
        j.id AS job_id,
        j.order_id,
        j.outsourcing_request_id,
        j.original_shop_id,
        j.executor_shop_id,
        j.awarded_price,
        j.status AS job_status,
        j.awarded_at,
        j.completion_date,
        j.notes AS job_notes,
        j.created_at AS job_created_at,
        j.updated_at AS job_updated_at,

        r.request_code,

        o.order_code,
        o.customer_name,
        o.service_type,
        o.item_name,
        o.quantity,
        o.size,
        o.due_date,
        o.payment_status,

        original_shop.shop_name AS original_shop_name,
        executor_shop.shop_name AS executor_shop_name

    FROM outsourced_jobs j

    LEFT JOIN outsourcing_requests r
        ON j.outsourcing_request_id = r.id

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

    LEFT JOIN users original_shop
        ON j.original_shop_id = original_shop.id

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

    WHERE j.original_shop_id = ?
       OR j.executor_shop_id = ?

    ORDER BY j.updated_at DESC, j.created_at DESC
");

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

$stmt->bind_param("ii", $current_user_id, $current_user_id);
$stmt->execute();
$jobs = $stmt->get_result();
?>

<div class="container-fluid px-0 job-tracking-page">

    <div class="d-flex justify-content-between align-items-center flex-wrap gap-3 mb-4">
        <div>
            <h1 class="fw-bold mb-1">Job Tracking</h1>
            <p class="text-muted mb-0">
                Monitor the progress of outsourced jobs handled by partner shops.
            </p>
        </div>

        <a href="admin.php?page=outsourced-jobs" class="btn btn-light border rounded-pill px-4">
            <i class="fa-solid fa-box me-1"></i> Outsourced Jobs
        </a>
    </div>

    <div class="row g-4">

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

                <?php
                $current_status = $job["job_status"] ?: "assigned";
                $progress = progressPercent($current_status);

                $is_original_shop = ((int)$job["original_shop_id"] === $current_user_id);
                $roleLabel = $is_original_shop ? "Outsourced by your shop" : "Assigned to your shop";

                $partnerLabel = $is_original_shop
                    ? ($job["executor_shop_name"] ?: "Partner Shop")
                    : ($job["original_shop_name"] ?: "Original Shop");
                ?>

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

                            <div class="d-flex justify-content-between align-items-start flex-wrap gap-3 mb-3">
                                <div>
                                    <span class="tracking-role">
                                        <?php echo h($roleLabel); ?>
                                    </span>

                                    <h4 class="fw-bold mb-1 mt-2">
                                        <?php echo h($job["order_code"] ?: "N/A"); ?>
                                    </h4>

                                    <p class="text-muted mb-0">
                                        Partner: <strong><?php echo h($partnerLabel); ?></strong>
                                    </p>
                                </div>

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

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

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

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

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

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

                            </div>

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

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

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

                                <div class="col-md-3">
                                    <div class="info-box">
                                        <small>Awarded Price</small>
                                        <strong>
                                            <?php
                                            echo $job["awarded_price"] !== null
                                                ? "₱" . number_format((float)$job["awarded_price"], 2)
                                                : "N/A";
                                            ?>
                                        </strong>
                                    </div>
                                </div>

                                <div class="col-md-3">
                                    <div class="info-box">
                                        <small>Last Updated</small>
                                        <strong><?php echo h(formatDateTime($job["job_updated_at"])); ?></strong>
                                    </div>
                                </div>

                            </div>

                            <div class="tracking-progress mb-4">
                                <div class="d-flex justify-content-between mb-2">
                                    <span class="fw-semibold">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 >= 25 ? 'active' : ''; ?>">Assigned</span>
                                    <span class="<?php echo $progress >= 50 ? 'active' : ''; ?>">In Progress</span>
                                    <span class="<?php echo $progress >= 75 ? 'active' : ''; ?>">Ready</span>
                                    <span class="<?php echo $progress >= 100 ? 'active' : ''; ?>">Completed</span>
                                </div>
                            </div>

                            <div class="tracking-note">
                                <small>Latest Note</small>
                                <p class="mb-0">
                                    <?php echo !empty($job["job_notes"]) ? nl2br(h($job["job_notes"])) : "No progress note yet."; ?>
                                </p>
                            </div>

                            <div class="d-flex justify-content-end flex-wrap gap-2 mt-4">
                                <a href="admin.php?page=order-details&id=<?php echo (int)$job["order_id"]; ?>" class="btn btn-outline-secondary">
                                    Order Details
                                </a>

                                <?php if ($is_original_shop): ?>
                                    <a href="admin.php?page=view-outsourcing-request&id=<?php echo (int)$job["outsourcing_request_id"]; ?>" class="btn btn-primary">
                                        View Request
                                    </a>
                                <?php else: ?>
                                    <a href="admin.php?page=outsourced-jobs" class="btn btn-success">
                                        Update in Outsourced Jobs
                                    </a>
                                <?php endif; ?>
                            </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-location-dot"></i>
                            <h5 class="fw-bold mb-1">No jobs to track yet</h5>
                            <p class="text-muted mb-0">
                                Outsourced jobs will appear here after a partner shop accepts and updates the job.
                            </p>
                        </div>
                    </div>
                </div>
            </div>

        <?php endif; ?>

    </div>

</div>

<style>
.job-tracking-page {
    width: 100%;
}

.job-tracking-page h1 {
    font-size: clamp(26px, 2vw, 36px);
    color: #111827;
}

.tracking-card {
    overflow: hidden;
}

.tracking-role {
    display: inline-block;
    font-size: 12px;
    font-weight: 700;
    color: #0369a1;
    background: #e0f2fe;
    border: 1px solid #bae6fd;
    padding: 6px 10px;
    border-radius: 999px;
}

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

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

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

.tracking-progress {
    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;
}

.tracking-note {
    background: #fff;
    border: 1px solid #eef2f7;
    border-radius: 18px;
    padding: 18px;
}

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

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

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