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

include_once __DIR__ . '/../../config/dbcon.php';
include_once __DIR__ . '/../../helpers/api_helper.php';
require_once __DIR__ . '/../../helpers/jwt_helper.php';


if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(405, "Invalid request method.");
}

$headers = getallheaders();
if (!isset($headers['Authorization'])) {
    sendResponse(401, "Authorization please login.");
}

$token = str_replace('Bearer ', '', $headers['Authorization']);


$decoded = verifyJWT($token);
if (!$decoded) {
    sendResponse(401, "Invalid or expired token.");
}

$userId = $decoded['user_id'];


$data = json_decode(file_get_contents("php://input"), true);
$jobId = intval($data['job_id'] ?? 0);

if ($jobId <= 0) {
    sendResponse(422, "Valid job_id is required.");
}

try {

    $checkStmt = $conn->prepare("
        SELECT id FROM saved_jobs 
        WHERE user_id = ? AND job_id = ?
        LIMIT 1
    ");
    $checkStmt->execute([$userId, $jobId]);

    if ($checkStmt->rowCount() > 0) {

        $deleteStmt = $conn->prepare("
            DELETE FROM saved_jobs 
            WHERE user_id = ? AND job_id = ?
        ");
        $deleteStmt->execute([$userId, $jobId]);

        sendResponse(200, "Job disliked successfully.", [
            'saved' => false
        ]);

    } else {

        $insertStmt = $conn->prepare("
            INSERT INTO saved_jobs (user_id, job_id)
            VALUES (?, ?)
        ");
        $insertStmt->execute([$userId, $jobId]);

        sendResponse(200, "Job liked successfully.", [
            'saved' => true
        ]);
    }

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