<?php
require_once __DIR__ . '/../config/db.php';
session_start();

// Ensure user is logged in
if (!isset($_SESSION['user_id'])) {
header('Location: ../pages/users/submit_application.php?error=upload_failed');
exit;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $send_to = $_POST['send_to'] ?? '';
    $sent_by = $_POST['sent_by'] ?? '';
    $subject = $_POST['subject'] ?? '';
    $notes = $_POST['notes'] ?? '';
    $user_id = $_SESSION['user_id'];

    // Handle file upload
    $file_path = null;
    if (isset($_FILES['fileUpload']) && $_FILES['fileUpload']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = __DIR__ . '/../uploads/';
        $originalFileName = basename($_FILES['fileUpload']['name']);
        $targetFile = $uploadDir . time() . '_' . $originalFileName;

        // Move the uploaded file
        if (move_uploaded_file($_FILES['fileUpload']['tmp_name'], $targetFile)) {
            $file_path = 'uploads/' . basename($targetFile); // Store relative path
        } else {
            die('File upload failed.');
        }
    }

    try {
        $stmt = $pdo->prepare("
            INSERT INTO submitted_applications (send_to, sent_by, subject, file_path, notes, user_id)
            VALUES (:send_to, :sent_by, :subject, :file_path, :notes, :user_id)
        ");

        $stmt->execute([
            ':send_to'   => $send_to,
            ':sent_by'   => $sent_by,
            ':subject'   => $subject,
            ':file_path' => $file_path,
            ':notes'     => $notes,
            ':user_id'   => $user_id
        ]);

        // Redirect or show success
        header('Location: ../pages/users/submit_application.php?success=1');
        exit;

    } catch (PDOException $e) {
header('Location: ../pages/users/submit_application.php?error=db_error');
exit;
    }
} else {
    echo "Invalid request method.";
}