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

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

$current_user_id = isset($_SESSION["user_id"]) ? (int)$_SESSION["user_id"] : 0;
$job_id = isset($_POST["job_id"]) ? (int)$_POST["job_id"] : 0;
$status = isset($_POST["status"]) ? trim($_POST["status"]) : "";
$notes = isset($_POST["notes"]) ? trim($_POST["notes"]) : "";

$allowed_statuses = [
    "assigned",
    "in_progress",
    "ready_for_pickup",
    "completed",
    "cancelled"
];

if ($current_user_id <= 0 || $job_id <= 0 || !in_array($status, $allowed_statuses)) {
    die("Invalid request.");
}

$stmt = $conn->prepare("
    SELECT id, executor_shop_id, order_id
    FROM outsourced_jobs
    WHERE id = ?
      AND executor_shop_id = ?
    LIMIT 1
");

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

$stmt->bind_param("ii", $job_id, $current_user_id);
$stmt->execute();
$result = $stmt->get_result();

if (!$result || $result->num_rows === 0) {
    die("Job not found or unauthorized.");
}

$job = $result->fetch_assoc();

if ($status === "completed") {
    $update = $conn->prepare("
        UPDATE outsourced_jobs
        SET status = ?,
            notes = ?,
            completion_date = NOW(),
            updated_at = NOW()
        WHERE id = ?
          AND executor_shop_id = ?
    ");

    $update->bind_param(
        "ssii",
        $status,
        $notes,
        $job_id,
        $current_user_id
    );
} else {
    $update = $conn->prepare("
        UPDATE outsourced_jobs
        SET status = ?,
            notes = ?,
            completion_date = NULL,
            updated_at = NOW()
        WHERE id = ?
          AND executor_shop_id = ?
    ");

    $update->bind_param(
        "ssii",
        $status,
        $notes,
        $job_id,
        $current_user_id
    );
}

if (!$update->execute()) {
    die("Failed to update job status: " . $update->error);
}

header("Location: admin.php?page=outsourced-jobs&message=status_updated");
exit;
?>