<?php
session_start();
require_once 'includes/auth_helpers.php';
redirect_if_not_authenticated();
redirect_if_no_permission('delete_files');

require_once 'db/config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $file_id = $_POST['file_id'] ?? null;
    $application_id = $_POST['application_id'] ?? null;

    if (!$file_id || !$application_id) {
        $_SESSION['message'] = 'Invalid request.';
        $_SESSION['message_type'] = 'danger';
        header('Location: index.php');
        exit();
    }

    try {
        $pdo = db();
        
        // First, get the filename to delete it from the server
        $stmt = $pdo->prepare("SELECT stored_filename FROM application_files WHERE id = ? AND application_id = ?");
        $stmt->execute([$file_id, $application_id]);
        $file = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($file) {
            $filepath = __DIR__ . '/uploads/' . $file['stored_filename'];

            // Delete the file from the filesystem
            if (file_exists($filepath)) {
                unlink($filepath);
            }

            // Delete the record from the database
            $delete_stmt = $pdo->prepare("DELETE FROM application_files WHERE id = ?");
            $delete_stmt->execute([$file_id]);

            $_SESSION['message'] = 'File deleted successfully.';
            $_SESSION['message_type'] = 'success';
        } else {
            $_SESSION['message'] = 'File not found or you do not have permission to delete it.';
            $_SESSION['message_type'] = 'danger';
        }

    } catch (PDOException $e) {
        // In a real app, log this error
        $_SESSION['message'] = 'Database error while deleting file.';
        $_SESSION['message_type'] = 'danger';
    }

    header('Location: view_application.php?id=' . $application_id);
    exit();

} else {
    header('Location: index.php');
    exit();
}