<?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;
$request_id = isset($_POST['request_id']) ? (int) $_POST['request_id'] : 0;

if ($current_user_id <= 0 || $request_id <= 0) {
    die("Invalid request.");
}

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

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

$contract_version = 'v1.0';
$contract_text_snapshot = mysqli_real_escape_string($conn, $_POST['contract_text'] ?? '');

$check_sql = "
    SELECT id
    FROM outsourcing_contract_acceptances
    WHERE outsourcing_request_id = $request_id
    LIMIT 1
";
$check_res = mysqli_query($conn, $check_sql);

if (mysqli_num_rows($check_res) == 0) {
    $insert_sql = "
        INSERT INTO outsourcing_contract_acceptances (
            outsourcing_request_id,
            accepted_by_shop_id,
            accepted_by_user_id,
            contract_version,
            contract_text_snapshot,
            accepted_at
        ) VALUES (
            $request_id,
            $current_user_id,
            $current_user_id,
            '$contract_version',
            '$contract_text_snapshot',
            NOW()
        )
    ";
    mysqli_query($conn, $insert_sql);

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

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