<?php
try {

    header("Content-Type: application/json");
    include_once dirname(__DIR__, 2) . "/config/dbcon.php";
    include_once dirname(__DIR__, 2) . "/helpers/api_helper.php";

    $input = json_decode(file_get_contents("php://input"), true);

    $draft_id = $input['draft_id'] ?? null;
    $job_name = $input['job_name'] ?? null;
    $job_type = $input['job_type'] ?? null;
    $job_description = $input['description'] ?? null;
    $job_salary = $input['job_salary'] ?? null;
    $job_positions = $input['job_positions'] ?? null;
    $apply = $input['apply'] ?? null;
    $is_featured = $input['is_featured'] ?? 0;
    $country_id = $input['country_id'] ?? null;
    $state_id = $input['state_id'] ?? null;
    $city_id = $input['city_id'] ?? null;
    $category_id = $input['category_id'] ?? null;
    $expiry_date = $input['expiry_date'] ?? null;


    // Validate related tables
    if ($country_id) {
        $stmt = $conn->prepare("SELECT id FROM countries WHERE id = ? AND deleted_at IS NULL");
        $stmt->execute([$country_id]);
        if (!$stmt->fetch())
            sendResponse(400, "Invalid country selected");
    }

    if ($state_id) {
        $stmt = $conn->prepare("SELECT id FROM states WHERE id = ? AND deleted_at IS NULL");
        $stmt->execute([$state_id]);
        if (!$stmt->fetch())
            sendResponse(400, "Invalid state selected");
    }

    if ($city_id) {
        $stmt = $conn->prepare("SELECT id FROM cities WHERE id = ? AND deleted_at IS NULL");
        $stmt->execute([$city_id]);
        if (!$stmt->fetch())
            sendResponse(400, "Invalid city selected");
    }


    // UPDATE / TOGGLE
    if ($draft_id) {

        $stmt = $conn->prepare("SELECT * FROM jobs WHERE id = ? AND deleted_at IS NULL");
        $stmt->execute([$draft_id]);
        $existing = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$existing)
            sendResponse(404, "Job does not exist or has been removed");


        // Already published -> just toggle is_draft
        if ($existing['is_published'] == 1) {

            $stmt = $conn->prepare("
                UPDATE jobs SET
                    is_draft = ?,
                    updated_at = NOW()
                WHERE id = ?
            ");

            $stmt->execute([
                $existing['is_draft'] == 1 ? 0 : 1,
                $draft_id
            ]);


            sendResponse(200, "Published job status updated successfully");
        }

        // Draft update
        $stmt = $conn->prepare("
            UPDATE jobs SET
                job_name = ?,
                job_type = ?,
                job_description = ?,
                job_salary = ?,
                job_available_positions = ?,
                apply = ?,
                is_featured = ?,
                country_id = ?,
                state_id = ?,
                city_id = ?,
                category_id = ?,
                expiry_date = ?,
                updated_at = NOW()
            WHERE id = ?
        ");

        $stmt->execute([
            $job_name ?? $existing['job_name'],
            $job_type ?? $existing['job_type'],
            $job_description ?? $existing['job_description'],
            $job_salary ?? $existing['job_salary'],
            $job_positions ?? $existing['job_available_positions'],
            $apply ?? $existing['apply'],
            $is_featured ?? $existing['is_featured'],
            $country_id ?? $existing['country_id'],
            $state_id ?? $existing['state_id'],
            $city_id ?? $existing['city_id'],
            $category_id ?? $existing['category_id'],
            $expiry_date ?? $existing['expiry_date'],
            $draft_id
        ]);

        sendResponse(200, "Draft updated successfully");
    }


    // CREATE NEW DRAFT
    $stmt = $conn->prepare("
        INSERT INTO jobs
        (job_name, job_type, job_description, job_salary, job_available_positions, apply, is_featured, country_id, state_id, city_id, category_id, expiry_date, is_draft)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    $stmt->execute([
        $job_name,
        $job_type,
        $job_description,
        $job_salary,
        $job_positions,
        $apply,
        $is_featured,
        $country_id,
        $state_id,
        $city_id,
        $category_id,
        $expiry_date,
        1
    ]);

    sendResponse(201, "Draft saved successfully");

} catch (PDOException $e) {
    sendResponse(500, "Something went wrong, please try again later");
}
