<?php
require_once '../includes/db_connect.php';

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

// Handle HTTP Methods
$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        handleGet($pdo);
        break;
    case 'POST':
        handlePost($pdo);
        break;
    case 'PUT':
        handlePut($pdo);
        break;
    case 'DELETE':
        handleDelete($pdo);
        break;
    default:
        http_response_code(405); // Method Not Allowed
        echo json_encode(['error' => 'Method not allowed']);
        break;
}

function handleGet($pdo) {
    if (isset($_GET['id'])) {
        // Get single job
        $stmt = $pdo->prepare("SELECT * FROM jobs WHERE id = ?");
        $stmt->execute([$_GET['id']]);
        $job = $stmt->fetch();
        if ($job) {
            echo json_encode($job);
        } else {
            http_response_code(404);
            echo json_encode(['error' => 'Job not found']);
        }
    } else {
        // Get all jobs with optional filters
        // Fix: Use posted_date instead of created_at
        $sql = "SELECT j.*, COUNT(a.id) as applicant_count 
                FROM jobs j 
                LEFT JOIN applications a ON j.id = a.job_id 
                GROUP BY j.id ORDER BY j.posted_date DESC";
        $stmt = $pdo->query($sql);
        $jobs = $stmt->fetchAll();
        echo json_encode($jobs);
    }
}

function handlePost($pdo) {
    $data = json_decode(file_get_contents('php://input'), true);
    
    // Basic validation
    if (!isset($data['title']) || !isset($data['department'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing required fields']);
        return;
    }

    $slug = createSlug($data['title']);
    // Ensure uniqueness (simple append)
    $stmtSlug = $pdo->prepare("SELECT id FROM jobs WHERE slug = ?");
    $stmtSlug->execute([$slug]);
    if ($stmtSlug->fetch()) {
        $slug .= '-' . uniqid();
    }

    $sql = "INSERT INTO jobs (title, department, location, type, status, description, requirements, slug) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt = $pdo->prepare($sql);
    
    try {
        $stmt->execute([
            $data['title'],
            $data['department'],
            $data['location'] ?? 'Remote',
            $data['type'] ?? 'Full-time',
            $data['status'] ?? 'Draft',
            $data['description'] ?? '',
            $data['requirements'] ?? '',
            $slug
        ]);
        http_response_code(201);
        echo json_encode(['id' => $pdo->lastInsertId(), 'message' => 'Job created successfully']);
    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
    }
}

// Simple PUT and DELETE placeholders for now
// Update Job
function handlePut($pdo) {
    $data = json_decode(file_get_contents('php://input'), true);

    if (!isset($data['id'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Job ID required for update']);
        return;
    }

    $sql = "UPDATE jobs SET 
            title = ?, department = ?, location = ?, type = ?, status = ?, description = ?, requirements = ? 
            WHERE id = ?";
    
    $stmt = $pdo->prepare($sql);

    try {
        $stmt->execute([
            $data['title'],
            $data['department'],
            $data['location'] ?? 'Remote',
            $data['type'] ?? 'Full-time',
            $data['status'] ?? 'Draft',
            $data['description'] ?? '',
            $data['requirements'] ?? '',
            $data['id']
        ]);
        echo json_encode(['message' => 'Job updated successfully']);
    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
    }
}

function handleDelete($pdo) {
     $data = json_decode(file_get_contents('php://input'), true);
     if (!isset($data['id'])) {
         http_response_code(400);
         echo json_encode(['error' => 'ID required']);
         return;
     }

     $stmt = $pdo->prepare("DELETE FROM jobs WHERE id = ?");
     $stmt->execute([$data['id']]);
     echo json_encode(['message' => 'Job deleted']);
}
function createSlug($string) {
    $slug = strtolower(trim($string));
    $slug = preg_replace('/[^a-z0-9-]/', '-', $slug);
    $slug = preg_replace('/-+/', '-', $slug);
    return trim($slug, '-');
}
?>
