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

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

if (!isset($_SESSION['user_id'])) {
    die("Unauthorized access.");
}

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: admin.php?page=outsourcing-requests");
    exit;
}

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

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

/*
|--------------------------------------------------------------------------
| MUST ACCEPT CONTRACT FIRST
|--------------------------------------------------------------------------
*/
$contract_check_sql = "
    SELECT id
    FROM outsourcing_contract_acceptances
    WHERE outsourcing_request_id = $request_id
    LIMIT 1
";
$contract_check_res = mysqli_query($conn, $contract_check_sql);

if (!$contract_check_res || mysqli_num_rows($contract_check_res) == 0) {
    die("You must accept the binding contract before responding.");
}

$quoted_price = isset($_POST['quoted_price']) && $_POST['quoted_price'] !== '' ? (float) $_POST['quoted_price'] : null;
$estimated_days = isset($_POST['estimated_days']) && $_POST['estimated_days'] !== '' ? (int) $_POST['estimated_days'] : null;
$remarks = trim($_POST['remarks'] ?? '');

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

/*
|--------------------------------------------------------------------------
| Validate request belongs to this shop
|--------------------------------------------------------------------------
*/
$request_sql = "
    SELECT *
    FROM outsourcing_requests
    WHERE id = $request_id
      AND target_shop_id = $current_user_id
    LIMIT 1
";
$request_res = mysqli_query($conn, $request_sql);

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

$request = mysqli_fetch_assoc($request_res);

/*
|--------------------------------------------------------------------------
| Prevent duplicate response
|--------------------------------------------------------------------------
*/
$check_sql = "
    SELECT id
    FROM outsourcing_responses
    WHERE outsourcing_request_id = $request_id
    LIMIT 1
";
$check_res = mysqli_query($conn, $check_sql);

if ($check_res && mysqli_num_rows($check_res) > 0) {
    die("You already responded to this request.");
}

/*
|--------------------------------------------------------------------------
| If accepted, save contract acceptance first
|--------------------------------------------------------------------------
*/
if ($response_status === 'accepted') {
    $contract_check_sql = "
        SELECT id
        FROM outsourcing_contract_acceptances
        WHERE outsourcing_request_id = $request_id
        LIMIT 1
    ";
    $contract_check_res = mysqli_query($conn, $contract_check_sql);

    if (!$contract_check_res || mysqli_num_rows($contract_check_res) == 0) {
        die("You must accept the binding contract before responding.");
    }
}


$remarks_esc = mysqli_real_escape_string($conn, $remarks);
$response_status_esc = mysqli_real_escape_string($conn, $response_status);

$quoted_price_sql = $quoted_price !== null ? $quoted_price : "NULL";
$estimated_days_sql = $estimated_days !== null ? $estimated_days : "NULL";

/*
|--------------------------------------------------------------------------
| Save response
|--------------------------------------------------------------------------
*/
$insert_sql = "
    INSERT INTO outsourcing_responses (
        outsourcing_request_id,
        responded_by_shop_id,
        responded_by_user_id,
        response_status,
        quoted_price,
        estimated_days,
        remarks,
        submitted_at
    ) VALUES (
        $request_id,
        $current_user_id,
        $current_user_id,
        '$response_status_esc',
        $quoted_price_sql,
        $estimated_days_sql,
        '$remarks_esc',
        NOW()
    )
";

if (!mysqli_query($conn, $insert_sql)) {
    die("Failed to save response: " . mysqli_error($conn));
}

/*
|--------------------------------------------------------------------------
| Update request status
|--------------------------------------------------------------------------
*/

$update_request_sql = "
    UPDATE outsourcing_requests
    SET status = 'responded'
    WHERE id = $request_id
";
mysqli_query($conn, $update_request_sql);


header("Location: admin.php?page=outsourcing-requests");
exit;