<?php
require_once __DIR__ . '/_helpers.php';
require_post();

$MAX_BYTES = 5 * 1024 * 1024;
$ALLOWED_EXT  = ['pdf', 'doc', 'docx'];
$ALLOWED_MIME = [
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
];

$f = [
    'name'           => clean($_POST['name']           ?? '', 120),
    'email'          => clean_email($_POST['email']    ?? ''),
    'phone'          => clean($_POST['phone']          ?? '', 40),
    'address'        => clean($_POST['address']        ?? '', 255),
    'city'           => clean($_POST['city']           ?? '', 100),
    'state'          => clean($_POST['state']          ?? '', 60),
    'zip'            => clean($_POST['zip']            ?? '', 20),
    'role'           => clean($_POST['role']           ?? '', 80),
    'over18'         => clean($_POST['over18']         ?? '', 10),
    'driverLicense'  => clean($_POST['driverLicense']  ?? '', 10),
    'ownsCar'        => clean($_POST['ownsCar']        ?? '', 10),
    'experience'     => clean($_POST['experience']     ?? '', 5000),
    'hearAbout'      => clean($_POST['hearAbout']      ?? '', 255),
];
$shifts = $_POST['shifts'] ?? [];
if (!is_array($shifts)) $shifts = [];
$shifts = array_map(function ($s) { return clean($s, 30); }, $shifts);
$token = $_POST['g-recaptcha-response'] ?? '';

if (!$f['name'] || !$f['email'] || !$f['phone']) {
    send_json(400, ['ok' => false, 'error' => 'Please fill in all required fields.']);
}
if (!verify_recaptcha($token)) {
    send_json(400, ['ok' => false, 'error' => 'reCAPTCHA verification failed. Please try again.']);
}

// Optional resume validation
$attachment = null;
if (!empty($_FILES['resume']) && $_FILES['resume']['error'] !== UPLOAD_ERR_NO_FILE) {
    $r = $_FILES['resume'];
    if ($r['error'] !== UPLOAD_ERR_OK) {
        send_json(400, ['ok' => false, 'error' => 'Resume upload failed. Please try again.']);
    }
    if ($r['size'] > $MAX_BYTES) {
        send_json(400, ['ok' => false, 'error' => 'Resume must be 5 MB or smaller.']);
    }
    $ext  = strtolower(pathinfo($r['name'], PATHINFO_EXTENSION));
    $mime = function_exists('mime_content_type') ? mime_content_type($r['tmp_name']) : $r['type'];
    if (!in_array($ext, $ALLOWED_EXT, true) && !in_array($mime, $ALLOWED_MIME, true)) {
        send_json(400, ['ok' => false, 'error' => 'Resume must be a PDF, DOC, or DOCX file.']);
    }
    $r['type'] = $mime ?: $r['type'];
    $attachment = $r;
}

$subject = "Job Application — {$f['name']}" . ($f['role'] ? " ({$f['role']})" : '');
$body  = "— APPLICANT —\n";
$body .= "Name:    {$f['name']}\n";
$body .= "Email:   {$f['email']}\n";
$body .= "Phone:   {$f['phone']}\n";
$body .= "Address: {$f['address']}\n";
$body .= "City/ST/Zip: {$f['city']}, {$f['state']} {$f['zip']}\n\n";
$body .= "— ROLE & ELIGIBILITY —\n";
$body .= "Role:             {$f['role']}\n";
$body .= "Over 18:          {$f['over18']}\n";
$body .= "Driver's License: {$f['driverLicense']}\n";
$body .= "Owns a Car:       {$f['ownsCar']}\n";
$body .= "Preferred Shifts: " . (count($shifts) ? implode(', ', $shifts) : '—') . "\n\n";
$body .= "— EXPERIENCE —\n{$f['experience']}\n\n";
$body .= "Heard about us via: {$f['hearAbout']}\n";
$body .= $attachment ? "\n(Resume attached: {$attachment['name']})\n" : "\n(No resume attached)\n";

if (!send_email($subject, $body, $attachment)) {
    send_json(500, ['ok' => false, 'error' => 'Server could not send email. Please try again later.']);
}

send_json(200, ['ok' => true]);
