<?php
/**
 * Get Application Details - AJAX endpoint
 * Returns detailed information about a specific job application
 */

require_once '../../config/database.php';
require_once '../../includes/auth.php';

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

// Check if user is logged in
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit();
}

$userId = $_SESSION['user_id'];
$applicationId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$applicationId) {
    echo json_encode(['success' => false, 'message' => 'Invalid application ID']);
    exit();
}

try {
    // Get application details with job ownership verification
    $application = fetchRow("
        SELECT 
            ja.*,
            jpu.full_name as applicant_name,
            jpu.email,
            jpu.phone,
            jpu.user_type,
            mp.skills as profession,
            j.title as job_title,
            DATE_FORMAT(ja.created_at, '%M %d, %Y at %h:%i %p') as application_date
        FROM job_applications ja
        JOIN job_portal_users jpu ON ja.job_portal_user_id = jpu.id
        JOIN jobs j ON ja.job_id = j.id
        LEFT JOIN member_profiles mp ON jpu.member_id = mp.member_id
        WHERE ja.id = ? AND j.posted_by_user_id = ?
    ", [$applicationId, $userId]);

    if (!$application) {
        echo json_encode(['success' => false, 'message' => 'Application not found or access denied']);
        exit();
    }

    // Format the response
    $response = [
        'success' => true,
        'application' => [
            'id' => $application['id'],
            'applicant_name' => $application['applicant_name'],
            'email' => $application['email'],
            'phone' => $application['phone'] ?: 'Not provided',
            'user_type' => ucfirst($application['user_type']),
            'profession' => $application['profession'],
            'cover_letter' => nl2br(htmlspecialchars($application['cover_letter'])),
            'status' => ucfirst($application['status']),
            'application_date' => $application['application_date'],
            'job_title' => $application['job_title']
        ]
    ];

    echo json_encode($response);

} catch (Exception $e) {
    error_log("Error fetching application details: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Database error occurred']);
}
?>
