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

$order_id = isset($_POST['order_id']) ? (int) $_POST['order_id'] : 0;
$target_shop_id = isset($_POST['target_shop_id']) ? (int) $_POST['target_shop_id'] : 0;
$request_message = trim($_POST['request_message'] ?? '');
$required_date = trim($_POST['required_date'] ?? '');

if ($order_id <= 0 || $target_shop_id <= 0) {
    die("Invalid form data.");
}

// fetch order
$sql_order = "
    SELECT id, shop_id, service_id, design_file
    FROM orders
    WHERE id = $order_id
      AND shop_id = $current_user_id
    LIMIT 1
";
$res_order = mysqli_query($conn, $sql_order);

if (!$res_order || mysqli_num_rows($res_order) === 0) {
    die("Order not found or not owned by your shop.");
}

$order = mysqli_fetch_assoc($res_order);

// upload attachment if any
$attachment_file = null;

if (!empty($_FILES['attachment_file']['name'])) {
    $upload_dir = __DIR__ . '/uploads/outsourcing/';
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }

    $original_name = basename($_FILES['attachment_file']['name']);
    $new_name = 'out_' . time() . '_' . $original_name;
    $target_path = $upload_dir . $new_name;

    if (move_uploaded_file($_FILES['attachment_file']['tmp_name'], $target_path)) {
        $attachment_file = 'uploads/outsourcing/' . $new_name;
    }
}

if ($attachment_file === null && !empty($order['design_file'])) {
    $attachment_file = $order['design_file'];
}

$request_code = 'OUT-' . date('YmdHis') . '-' . rand(100, 999);

$request_code_esc = mysqli_real_escape_string($conn, $request_code);
$request_message_esc = mysqli_real_escape_string($conn, $request_message);
$required_date_sql = $required_date !== '' ? "'" . mysqli_real_escape_string($conn, $required_date) . "'" : "NULL";
$attachment_sql = $attachment_file ? "'" . mysqli_real_escape_string($conn, $attachment_file) . "'" : "NULL";

$sql_insert = "
    INSERT INTO outsourcing_requests (
        request_code,
        order_id,
        requester_shop_id,
        target_shop_id,
        requested_by,
        service_id,
        request_message,
        required_date,
        attachment_file,
        status,
        is_selected,
        sent_at,
        created_at,
        updated_at
    ) VALUES (
        '$request_code_esc',
        {$order['id']},
        {$order['shop_id']},
        $target_shop_id,
        $current_user_id,
        " . (!empty($order['service_id']) ? (int)$order['service_id'] : "NULL") . ",
        '$request_message_esc',
        $required_date_sql,
        $attachment_sql,
        'sent',
        0,
        NOW(),
        NOW(),
        NOW()
    )
";

if (!mysqli_query($conn, $sql_insert)) {
    die("Failed to save outsourcing request: " . mysqli_error($conn));
}

mysqli_query($conn, "UPDATE orders SET status = 'needs_outsourcing' WHERE id = $order_id");

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