<?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"];
$message = $_GET["message"] ?? "";

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";
}

$stmt = $conn->prepare("
    SELECT 
        j.id AS job_id,
        j.order_id,
        j.outsourcing_request_id,
        j.outsourcing_response_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.created_at DESC
");

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

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

<div class="container-fluid px-0 outsourced-jobs-page">

    <div class="d-flex justify-content-between align-items-center flex-wrap gap-3 mb-4">
        <div>
            <h1 class="fw-bold mb-1">Outsourced Jobs</h1>
            <p class="text-muted mb-0">
                Monitor outsourced orders and update assigned job progress.
            </p>
        </div>

        <a href="admin.php?page=orders" class="btn btn-light border rounded-pill px-4">
            <i class="fa-solid fa-arrow-left me-1"></i> Back to Orders
        </a>
    </div>

    <?php if ($message === "outsourced"): ?>
        <div class="alert alert-success rounded-3">
            Order successfully moved to Outsourced Jobs.
        </div>
    <?php elseif ($message === "status_updated"): ?>
        <div class="alert alert-success rounded-3">
            Job status updated successfully.
        </div>
    <?php endif; ?>

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

            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0 outsourced-table">
                    <thead>
                        <tr>
                            <th>Request Code</th>
                            <th>Order Code</th>
                            <th>Customer</th>
                            <th>Original Shop</th>
                            <th>Executor Shop</th>
                            <th>Item</th>
                            <th>Qty</th>
                            <th>Size</th>
                            <th>Due Date</th>
                            <th>Awarded Price</th>
                            <th>Payment</th>
                            <th>Job Status</th>
                            <th>Last Update</th>
                            <th>Update Progress</th>
                            <th>Action</th>
                        </tr>
                    </thead>

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

                                <?php
                                $is_original_shop = ((int)$job["original_shop_id"] === $current_user_id);
                                $is_executor_shop = ((int)$job["executor_shop_id"] === $current_user_id);

                                $request_link = $is_original_shop
                                    ? "admin.php?page=view-outsourcing-request&id=" . (int)$job["outsourcing_request_id"]
                                    : "admin.php?page=view-incoming-outsourcing-request&id=" . (int)$job["outsourcing_request_id"];

                                $current_status = $job["job_status"] ?: "assigned";
                                ?>

                                <tr>
                                    <td class="fw-semibold">
                                        <?php echo h($job["request_code"] ?: "N/A"); ?>
                                    </td>

                                    <td>
                                        <?php echo h($job["order_code"] ?: "N/A"); ?>
                                    </td>

                                    <td>
                                        <?php echo h($job["customer_name"] ?: "N/A"); ?>
                                    </td>

                                    <td>
                                        <?php echo h($job["original_shop_name"] ?: "N/A"); ?>
                                    </td>

                                    <td>
                                        <?php echo h($job["executor_shop_name"] ?: "N/A"); ?>
                                    </td>

                                    <td>
                                        <?php echo h($job["item_name"] ?: "N/A"); ?>
                                    </td>

                                    <td>
                                        <?php echo (int)($job["quantity"] ?? 0); ?>
                                    </td>

                                    <td>
                                        <?php echo h($job["size"] ?: "N/A"); ?>
                                    </td>

                                    <td>
                                        <?php echo h(formatDateOnly($job["due_date"])); ?>
                                    </td>

                                    <td>
                                        <?php
                                        echo $job["awarded_price"] !== null
                                            ? "₱" . number_format((float)$job["awarded_price"], 2)
                                            : "N/A";
                                        ?>
                                    </td>

                                    <td>
                                        <span class="badge rounded-pill bg-light text-dark border px-3 py-2">
                                            <?php echo h(ucfirst($job["payment_status"] ?: "N/A")); ?>
                                        </span>
                                    </td>

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

                                    <td>
                                        <?php echo h(formatDateTime($job["job_updated_at"])); ?>
                                    </td>

                                    <td>
                                        <?php if ($is_executor_shop): ?>
                                            <form action="update_outsourced_job_status.php" method="POST" class="job-status-form">
                                                <input type="hidden" name="job_id" value="<?php echo (int)$job["job_id"]; ?>">

                                                <select name="status" class="form-select form-select-sm mb-2">
                                                    <option value="assigned" <?php echo $current_status === "assigned" ? "selected" : ""; ?>>
                                                        Assigned
                                                    </option>

                                                    <option value="in_progress" <?php echo $current_status === "in_progress" ? "selected" : ""; ?>>
                                                        In Progress
                                                    </option>

                                                    <option value="ready_for_pickup" <?php echo $current_status === "ready_for_pickup" ? "selected" : ""; ?>>
                                                        Ready for Pickup
                                                    </option>

                                                    <option value="completed" <?php echo $current_status === "completed" ? "selected" : ""; ?>>
                                                        Completed
                                                    </option>

                                                    <option value="cancelled" <?php echo $current_status === "cancelled" ? "selected" : ""; ?>>
                                                        Cancelled
                                                    </option>
                                                </select>

                                                <textarea 
                                                    name="notes" 
                                                    class="form-control form-control-sm mb-2" 
                                                    rows="2" 
                                                    placeholder="Progress note..."
                                                ><?php echo h($job["job_notes"]); ?></textarea>

                                                <button type="submit" class="btn btn-sm btn-success w-100">
                                                    Update
                                                </button>
                                            </form>
                                        <?php else: ?>
                                            <span class="text-muted small">
                                                Monitoring only
                                            </span>
                                        <?php endif; ?>
                                    </td>

                                    <td>
                                        <div class="d-flex flex-column gap-1">
                                            <a href="<?php echo $request_link; ?>" class="btn btn-sm btn-outline-primary">
                                                View Request
                                            </a>

                                            <a href="admin.php?page=order-details&id=<?php echo (int)$job["order_id"]; ?>" class="btn btn-sm btn-outline-secondary">
                                                Order Details
                                            </a>
                                        </div>
                                    </td>
                                </tr>

                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="15">
                                    <div class="empty-state">
                                        <i class="fa-solid fa-box-open"></i>
                                        <p class="mb-0">No outsourced jobs found.</p>
                                    </div>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>

                </table>
            </div>

        </div>
    </div>

</div>

<style>
.outsourced-jobs-page {
    width: 100%;
}

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

.outsourced-table {
    min-width: 1550px;
}

.outsourced-table thead th {
    background: #f8fafc;
    color: #111827;
    font-size: 13px;
    font-weight: 700;
    padding: 14px;
    white-space: nowrap;
    border-bottom: 1px solid #e5e7eb;
}

.outsourced-table tbody td {
    padding: 14px;
    font-size: 13px;
    white-space: nowrap;
    border-bottom: 1px solid #f0f0f0;
    vertical-align: top;
}

.outsourced-table tbody tr:hover {
    background: #f9fbff;
}

.job-status-form {
    min-width: 190px;
}

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

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

@media (max-width: 768px) {
    .outsourced-table {
        min-width: 1450px;
    }

    .outsourced-table thead th,
    .outsourced-table tbody td {
        padding: 12px;
        font-size: 12px;
    }
}
</style>