<?php
/**
 * DWSK - Careers application submission handler
 * ---------------------------------------------------------------
 * Accepts multipart/form-data POST from the Careers form, validates
 * everything server-side, requires at least one CV/document upload,
 * stores files securely, emails HR + an acknowledgement to the
 * applicant, and returns a JSON response.
 *
 * PHP 8.2+ / Truehost cPanel compatible.
 */

define('DWSK_APP', true);

require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/helpers.php';
require_once __DIR__ . '/includes/mailer.php';

header('X-Content-Type-Options: nosniff');

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        json_response(false, 'Invalid request method.', [], 405);
    }

    // ---- Anti-spam: honeypot -------------------------------------------------
    if (is_spam_honeypot()) {
        json_response(true, 'Thank you for your application. Your documents have been submitted successfully. Only shortlisted candidates will be contacted.');
    }

    // ---- Anti-spam: rate limiting --------------------------------------------
    $ip = client_ip();
    if (!rate_limit_allow($ip)) {
        json_response(false, 'Too many submissions detected. Please wait a moment and try again.', [], 429);
    }

    // ---- CSRF check -------------------------------------------------------------
    $csrfToken = $_POST['csrf_token'] ?? '';
    if (!verify_csrf_token($csrfToken)) {
        json_response(false, 'Your session has expired. Please refresh the page and try again.', [], 419);
    }

    // ---- Optional reCAPTCHA -------------------------------------------------------
    if (RECAPTCHA_ENABLED && !recaptcha_passes($_POST['recaptcha_token'] ?? null)) {
        json_response(false, 'Verification failed. Please try again.', [], 400);
    }

    // ---- Collect + validate fields -------------------------------------------------
    $fullName = clean_text($_POST['full_name'] ?? '', 200);
    $email    = clean_text($_POST['email'] ?? '', 200);
    $spec     = clean_text($_POST['specialization'] ?? '', 300);
    $exp      = clean_text($_POST['experience'] ?? '', 5000);

    if ($fullName === '') {
        json_response(false, 'Please enter your full name.');
    }
    if ($email === '') {
        json_response(false, 'Please enter your email address.');
    }
    if (!is_valid_email($email)) {
        json_response(false, 'Invalid email address.');
    }

    // ---- CV / documents (at least one required) ------------------------------------
    $filesResult = collect_uploaded_files('documents');
    if (!$filesResult['ok']) {
        json_response(false, $filesResult['error']);
    }
    if (empty($filesResult['files'])) {
        json_response(false, 'Please upload your document.');
    }

    $storedFiles = store_uploaded_files($filesResult['files'], UPLOAD_DIR_CAREERS);

    // ---- Generate unique reference -------------------------------------------------
    $reference = generate_submission_id('APP');

    // ---- Build HR notification email --------------------------------------------
    $items = array_map(fn($f) => '<li>' . e($f['original_name']) . '</li>', $storedFiles);
    $fileListHtml = '<p><strong>Attached documents:</strong></p><ul>' . implode('', $items) . '</ul>';

    $adminBody = "
        <p><strong>Application Reference:</strong> " . e($reference) . "</p>
        <p><strong>Full Name:</strong> " . e($fullName) . "</p>
        <p><strong>Email:</strong> " . e($email) . "</p>
        <p><strong>Area of Specialization:</strong> " . e($spec) . "</p>
        <p><strong>Experience Summary:</strong><br>" . nl2br(e($exp)) . "</p>
        {$fileListHtml}
        <p style='color:#64748B;font-size:12.5px;'>Submitted " . e(date('Y-m-d H:i:s')) . " from IP " . e($ip) . "</p>
    ";
    $adminHtml = dwsk_email_template('New Career Application — ' . $reference, $adminBody);

    $attachmentsForAdmin = array_map(fn($f) => ['path' => $f['stored_path'], 'name' => $f['original_name']], $storedFiles);

    $adminSent = send_branded_email(
        ADMIN_EMAIL_CAREERS,
        'New Career Application - ' . $fullName . ' (' . $reference . ')',
        $adminHtml,
        $attachmentsForAdmin,
        $email
    );

    // ---- Build applicant acknowledgement email ------------------------------------
    $clientBody = "
        <p>Thank you for your application.</p>
        <p><strong>Application Reference:</strong> " . e($reference) . "</p>
        <p>Your documents have been submitted successfully.</p>
        <p>Only shortlisted candidates will be contacted.</p>
    ";
    $clientHtml = dwsk_email_template('Application Received — Thank You', $clientBody);
    $clientSent = send_branded_email($email, 'Your Application Confirmation - ' . $reference, $clientHtml);

    // ---- Log submission ------------------------------------------------------------
    log_submission(LOG_FILE_CAREERS, [
        'reference' => $reference,
        'ip'        => $ip,
        'full_name' => $fullName,
        'email'     => $email,
        'specialization' => $spec,
        'files'     => array_map(fn($f) => $f['stored_name'], $storedFiles),
        'admin_email_sent'  => $adminSent,
        'client_email_sent' => $clientSent,
    ]);

    json_response(true, 'Thank you for your application. Your documents have been submitted successfully. Only shortlisted candidates will be contacted.', [
        'reference' => $reference,
    ]);

} catch (\Throwable $e) {
    log_error('submit_application', $e);
    json_response(false, 'Submission failed. Please try again later.', [], 500);
}
