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

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

$current_user_id = $_SESSION['user_id'] ?? 0;

if (!$current_user_id) {
    die("Unauthorized access.");
}

$request_id = isset($_POST['request_id']) ? (int) $_POST['request_id'] : 0;
$decision   = isset($_POST['decision']) ? trim($_POST['decision']) : '';

if ($request_id <= 0 || !in_array($decision, ['accepted', 'held', 'declined'])) {
    die("Invalid request.");
}

$sql = "
    SELECT *
    FROM outsourcing_requests
    WHERE id = $request_id
      AND requester_shop_id = $current_user_id
    LIMIT 1
";
$res = mysqli_query($conn, $sql);

if (!$res || mysqli_num_rows($res) == 0) {
    die("Request not found.");
}

$request = mysqli_fetch_assoc($res);

$decision_esc = mysqli_real_escape_string($conn, $decision);

/*
|--------------------------------------------------------------------------
| Update final requester decision
|--------------------------------------------------------------------------
*/
$update_sql = "
    UPDATE outsourcing_requests
    SET status = '$decision_esc',
        reviewed_at = NOW()
    WHERE id = $request_id
";

if (!mysqli_query($conn, $update_sql)) {
    die("Failed to update request status: " . mysqli_error($conn));
}

/*
|--------------------------------------------------------------------------
| If accepted, create outsourced job
|--------------------------------------------------------------------------
*/
if ($decision === 'accepted') {
    $check_job_sql = "
        SELECT id
        FROM outsourced_jobs
        WHERE outsourcing_request_id = $request_id
        LIMIT 1
    ";
    $check_job_res = mysqli_query($conn, $check_job_sql);

    if ($check_job_res && mysqli_num_rows($check_job_res) == 0) {
        $response_sql = "
            SELECT *
            FROM outsourcing_responses
            WHERE outsourcing_request_id = $request_id
            LIMIT 1
        ";
        $response_res = mysqli_query($conn, $response_sql);

        if (!$response_res || mysqli_num_rows($response_res) == 0) {
            die("No outsourcing response found.");
        }

        $response = mysqli_fetch_assoc($response_res);

        $quoted_price = isset($response['quoted_price']) && $response['quoted_price'] !== null
            ? (float)$response['quoted_price']
            : "NULL";

        $insert_job_sql = "
            INSERT INTO outsourced_jobs (
                order_id,
                outsourcing_request_id,
                outsourcing_response_id,
                original_shop_id,
                executor_shop_id,
                awarded_price,
                status,
                awarded_by,
                awarded_at,
                completion_date,
                notes,
                created_at,
                updated_at
            ) VALUES (
                {$request['order_id']},
                $request_id,
                {$response['id']},
                {$request['requester_shop_id']},
                {$request['target_shop_id']},
                " . ($quoted_price === "NULL" ? "NULL" : $quoted_price) . ",
                'assigned',
                $current_user_id,
                NOW(),
                NULL,
                NULL,
                NOW(),
                NOW()
            )
        ";

        if (!mysqli_query($conn, $insert_job_sql)) {
            die("Failed to create outsourced job: " . mysqli_error($conn));
        }
    }
}

header("Location: admin.php?page=view-outsourcing-request&id=$request_id");
exit;