<?php
/**
 * Get Application Attachments - AJAX endpoint
 * Returns attachments for 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 {
    // First verify that the user owns the job for this application
    $jobOwnership = fetchRow("
        SELECT j.id 
        FROM jobs j
        JOIN job_applications ja ON j.id = ja.job_id
        WHERE ja.id = ? AND j.posted_by_user_id = ?
    ", [$applicationId, $userId]);

    if (!$jobOwnership) {
        error_log("Attachments access denied - Application ID: $applicationId, User ID: $userId");
        echo json_encode(['success' => false, 'message' => 'Application not found or access denied']);
        exit();
    }

    // Check if application_media table exists
    $tableExists = fetchRow("SHOW TABLES LIKE 'application_media'");
    if (!$tableExists) {
        error_log("application_media table does not exist");
        echo json_encode(['success' => false, 'message' => 'Attachments table not found']);
        exit();
    }

    // Get attachments for this application
    $attachments = fetchAll("
        SELECT 
            id,
            file_name,
            file_path,
            file_size,
            media_type,
            created_at
        FROM application_media 
        WHERE application_id = ?
        ORDER BY created_at DESC
    ", [$applicationId]);

    error_log("Attachments query result for application $applicationId: " . count($attachments) . " records found");

    // Format file sizes and paths
    $formattedAttachments = [];
    foreach ($attachments as $attachment) {
        $formattedAttachments[] = [
            'id' => $attachment['id'],
            'file_name' => $attachment['file_name'],
            'file_path' => $attachment['file_path'],
            'file_size' => (int)$attachment['file_size'],
            'media_type' => ucfirst($attachment['media_type']),
            'created_at' => $attachment['created_at']
        ];
    }

    $response = [
        'success' => true,
        'attachments' => $formattedAttachments,
        'debug' => [
            'application_id' => $applicationId,
            'user_id' => $userId,
            'attachment_count' => count($formattedAttachments)
        ]
    ];

    echo json_encode($response);

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