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

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

try {

    // Allow only POST
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        sendResponse(405, "Only POST method is allowed.");
    }

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

    if (empty($input['category_id'])) {
        sendResponse(422, "Category ID is required.");
    }

    $categoryId = (int) $input['category_id'];

    // Pagination (from POST body)
    $limit = isset($input['limit']) && is_numeric($input['limit']) ? (int) $input['limit'] : 10;
    $offset = isset($input['offset']) && is_numeric($input['offset']) ? (int) $input['offset'] : 0;

    // Fetch jobs by category with pagination
    $stmt = $conn->prepare("
        SELECT 
            j.id,
            j.job_name,
            j.job_type,
            j.job_description,
            j.job_salary,
            j.job_available_positions,
            j.is_featured,
            j.apply,
            j.expiry_date,
            j.category_id,
            j.country_id,
            j.state_id,
            j.city_id,
            c.country_name,
            c.country_currency,
            s.state_name,
            ci.city_name,
            cat.category_name
        FROM jobs j
        INNER JOIN countries c ON j.country_id = c.id
        LEFT JOIN states s ON j.state_id = s.id
        LEFT JOIN cities ci ON j.city_id = ci.id
        INNER JOIN categories cat ON j.category_id = cat.id
        WHERE j.category_id = :category_id
          AND j.deleted_at IS NULL
          AND j.is_published = 1
        ORDER BY j.created_at DESC
        LIMIT :limit OFFSET :offset
    ");

    // Bind params
    $stmt->bindValue(':category_id', $categoryId, PDO::PARAM_INT);
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);

    $stmt->execute();
    $jobs = $stmt->fetchAll(PDO::FETCH_ASSOC);

    sendResponse(
        200,
        "Jobs fetched successfully.",
        [
            'category_id' => $categoryId,
            'limit' => $limit,
            'offset' => $offset,
            'jobs' => $jobs
        ]
    );

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