<?php
header('Content-Type: application/json');
session_start();

include_once __DIR__ . '/../../config/dbcon.php'; // PDO connection
include_once __DIR__ . '/../../helpers/api_helper.php';

if (!isset($_SESSION['user_id'])) {
    sendResponse(401, "Please login first.");
}

$data = json_decode(file_get_contents('php://input'), true);
$job_id = $data['job_id'];
$user_id = $_SESSION['user_id'];

try {
    // Check if the job is actually saved
    $stmt = $conn->prepare("SELECT 1 FROM saved_jobs WHERE user_id = :user_id AND job_id = :job_id LIMIT 1");
    $stmt->execute(['user_id' => $user_id, 'job_id' => $job_id]);

    if ($stmt->rowCount() === 0) {
        sendResponse(400, "Job not saved.");
    }

    // Delete the saved job
    $stmt = $conn->prepare("DELETE FROM saved_jobs WHERE user_id = :user_id AND job_id = :job_id");
    $stmt->execute(['user_id' => $user_id, 'job_id' => $job_id]);

    sendResponse(200, "Job unsaved successfully.");

} catch (PDOException $e) {
    sendResponse(500, "Database error: " . $e->getMessage());
}
