<?php
session_start();
require_once __DIR__ . '/../../config/dbcon.php';
include_once __DIR__ . '/../../helpers/api_helper.php';

header('Content-Type: application/json');

$userId = $_SESSION['user_id'] ?? 0;
if (!$userId) {
    sendResponse(401, 'Unauthorized access');
}

/* ✅ Read JSON input */
$input = json_decode(file_get_contents("php://input"), true);
$job_id = (int) ($input['job_id'] ?? 0);

if (!$job_id) {
    sendResponse(422, 'Invalid job ID');
}

try {

    /* ✅ Ownership check */
    $checkSql = "
        SELECT id
        FROM jobs
        WHERE id = :job_id
        AND created_by = :user_id
        LIMIT 1
    ";
    $checkStmt = $conn->prepare($checkSql);
    $checkStmt->execute([
        ':job_id' => $job_id,
        ':user_id' => $userId
    ]);

    if ($checkStmt->rowCount() === 0) {
        sendResponse(404, 'Job not found or permission denied');
    }

    /* ✅ Delete */
    $deleteSql = "
    UPDATE jobs 
    SET deleted_at = NOW() 
    WHERE id = :job_id 
    AND created_by = :user_id
    AND deleted_at IS NULL
";
    $deleteStmt = $conn->prepare($deleteSql);
    $deleteStmt->execute([
        ':job_id' => $job_id,
        ':user_id' => $userId
    ]);

    sendResponse(200, 'Job deleted successfully');

} catch (PDOException $e) {
    sendResponse(500, 'Failed to delete job');
}
