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

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

// Helper to handle file upload
function uploadFile($file, $destinationDir) {
    if (!isset($file) || $file['error'] !== UPLOAD_ERR_OK) {
        return null;
    }
    
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = uniqid() . '.' . $ext;
    
    if (!is_dir($destinationDir)) {
        mkdir($destinationDir, 0777, true);
    }
    
    if (move_uploaded_file($file['tmp_name'], $destinationDir . $filename)) {
        return $destinationDir . $filename;
    }
    return null;
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // 1. Fetch Job Details for Public View
    $id = $_GET['id'] ?? null;
    $slug = $_GET['slug'] ?? null;

    if(!$id && !$slug) {
        http_response_code(400);
        echo json_encode(['error' => 'Job ID or Slug required']);
        exit;
    }

    if ($slug) {
        $stmt = $pdo->prepare("SELECT id, title, department, location, type, description, requirements FROM jobs WHERE slug = ? AND status = 'Active'");
        $stmt->execute([$slug]);
    } else {
        $stmt = $pdo->prepare("SELECT id, title, department, location, type, description, requirements FROM jobs WHERE id = ? AND status = 'Active'");
        $stmt->execute([$id]);
    }
    
    $job = $stmt->fetch();

    if($job) {
        echo json_encode($job);
    } else {
        http_response_code(404);
        echo json_encode(['error' => 'Job not found or closed']);
    }

} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 2. Submit Application
    // Note: We use $_POST because of FormData (multipart/form-data)

    $jobId = $_POST['job_id'] ?? null;
    $fullName = $_POST['full_name'] ?? null;
    $email = $_POST['email'] ?? null;
    $phone = $_POST['phone'] ?? null;
    
    if (!$jobId || !$fullName || !$email) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing required fields']);
        exit;
    }

    // A. Handle Resume Upload
    $uploadDir = '../uploads/resumes/';
    $resumePath = null;
    if (isset($_FILES['resume'])) {
        $resumePath = uploadFile($_FILES['resume'], $uploadDir);
    }
    
    // B. Check/Create Candidate
    try {
        $pdo->beginTransaction();

        // Check if candidate exists by email
        $stmt = $pdo->prepare("SELECT id FROM candidates WHERE email = ?");
        $stmt->execute([$email]);
        $candidate = $stmt->fetch();
        $candidateId = null;

        if ($candidate) {
            $candidateId = $candidate['id'];
            // Update candidate info if provided (optional, maybe keep existing)
            // For now, let's just update phone/resume if new ones provided
            $stmtUpdate = $pdo->prepare("UPDATE candidates SET resume_path = COALESCE(?, resume_path), phone = COALESCE(?, phone) WHERE id = ?");
            $stmtUpdate->execute([$resumePath, $phone, $candidateId]);
        } else {
            // Create new candidate
            $stmtInsert = $pdo->prepare("INSERT INTO candidates (full_name, email, phone, resume_path) VALUES (?, ?, ?, ?)");
            $stmtInsert->execute([$fullName, $email, $phone, $resumePath]);
            $candidateId = $pdo->lastInsertId();
        }

        // C. Parse Custom Answers
        $answers = [];
        if (isset($_POST['answers']) && is_array($_POST['answers'])) {
            // We just store them as indexed array for now, 
            // ideally we'd map them back to the questions.
            // But since the frontend sends them in order, we trust the order.
            $answers = $_POST['answers'];
        }
        $answersJson = json_encode($answers);

        // D. Calculate Match Score
        // Fetch Job Details for scoring
        $stmtJob = $pdo->prepare("SELECT title, description, requirements FROM jobs WHERE id = ?");
        $stmtJob->execute([$jobId]);
        $jobData = $stmtJob->fetch();
        
        $candidateText = ($fullName . ' ' . $_POST['cover_letter'] . ' ' . implode(' ', $answers));
        $matchScore = calculateMatchScore($jobData, $candidateText);

        // E. Create Application
        // Check if already applied?
        $stmtCheck = $pdo->prepare("SELECT id FROM applications WHERE job_id = ? AND candidate_id = ?");
        $stmtCheck->execute([$jobId, $candidateId]);
        if ($stmtCheck->fetch()) {
             throw new Exception('You have already applied for this position.');
        }

        $stmtApp = $pdo->prepare("INSERT INTO applications (job_id, candidate_id, cover_letter, answers, match_score, status) VALUES (?, ?, ?, ?, ?, 'New')");
        $stmtApp->execute([
            $jobId, 
            $candidateId, 
            $_POST['cover_letter'] ?? '', 
            $answersJson,
            $matchScore
        ]);
        $applicationId = $pdo->lastInsertId();

        // D. Create Notification
        try {
            // Get job title for message
            $stmtJob = $pdo->prepare("SELECT title FROM jobs WHERE id = ?");
            $stmtJob->execute([$jobId]);
            $jobTitle = $stmtJob->fetchColumn();

            $notifMessage = "New application for {$jobTitle} from {$fullName}";
            $stmtNotif = $pdo->prepare("INSERT INTO notifications (type, message, related_id) VALUES ('New Application', ?, ?)");
            $stmtNotif->execute([$notifMessage, $applicationId]);
        } catch (Exception $e) {
            // Ignore notification errors to not block application success
        }

        $pdo->commit();
        echo json_encode(['success' => true, 'message' => 'Application submitted successfully', 'application_id' => $applicationId]);

    } catch (Exception $e) {
        $pdo->rollBack();
        http_response_code(500);
        echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
    }
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
}

// Simple Keyword Matching Algorithm
function calculateMatchScore($job, $candidateText) {
    if (!$job) return 0;

    $stopWords = ['a','an','the','and','or','but','in','on','at','to','for','with','by','is','are','was','were','be','been','have','has','had','do','does','did','of','it','this','that','these','those','i','you','he','she','we','they','my','your','his','her','our','their','what','which','who','whom','whose','when','where','why','how','all','any','both','each','few','more','most','other','some','such','no','nor','not','only','own','same','so','than','too','very','can','will','just','should','now'];

    // 1. Extract Keywords from Job
    $textToAnalyze = strtolower($job['title'] . ' ' . $job['description']);
    // giving title more weight by adding it twice
    $textToAnalyze .= ' ' . strtolower($job['title']); 
    
    // Clean text
    $textToAnalyze = preg_replace('/[^a-z0-9\s]/', '', $textToAnalyze);
    $words = explode(' ', $textToAnalyze);
    
    $keywords = [];
    foreach($words as $word) {
        $word = trim($word);
        if(strlen($word) > 2 && !in_array($word, $stopWords)) {
            $keywords[] = $word;
        }
    }
    
    $keywords = array_unique($keywords);
    $totalKeywords = count($keywords);
    
    if ($totalKeywords === 0) return 0;

    // 2. Scan Candidate Text
    $candidateText = strtolower($candidateText);
    $matches = 0;
    
    foreach($keywords as $word) {
        if (strpos($candidateText, $word) !== false) {
            $matches++;
        }
    }
    
    // 3. Calculate Percentage
    $score = ($matches / $totalKeywords) * 100;
    
    // Boost score slightly if resume attached (implicit trust) or other factors? 
    // For now, keep it strict to content match.
    
    return min(100, round($score));
}
?>
