<?php
require_once __DIR__ . '/includes/mail-helper.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception as PHPMailerException;

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

$name    = $_POST['name']    ?? '';
$phone   = $_POST['phone']   ?? '';
$profile = $_POST['profile'] ?? '';
$message = $_POST['message'] ?? '';
$recaptchaToken = $_POST['g-recaptcha-response'] ?? '';

if (trim($name) === '' || trim($phone) === '' || trim($profile) === '') {
    gx_json(false, 'Please fill in all required fields.');
}

if (!gx_verify_recaptcha($recaptchaToken)) {
    gx_json(false, 'reCAPTCHA verification failed. Please try again.');
}

// ---- Validate resume upload ----
if (empty($_FILES['resume']) || $_FILES['resume']['error'] !== UPLOAD_ERR_OK) {
    gx_json(false, 'Please upload your CV / Resume.');
}

$file = $_FILES['resume'];

if ($file['size'] > GX_UPLOAD_MAX_BYTES) {
    gx_json(false, 'Resume file is too large. Max size is 5MB.');
}

$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($ext, GX_UPLOAD_ALLOWED_EXT, true)) {
    gx_json(false, 'Invalid file type. Only PDF, DOC, DOCX are allowed.');
}

// Save the resume to disk with a safe, unique filename
if (!is_dir(GX_UPLOAD_DIR)) {
    mkdir(GX_UPLOAD_DIR, 0755, true);
}
$safeName  = preg_replace('/[^A-Za-z0-9_\-]/', '_', pathinfo($file['name'], PATHINFO_FILENAME));
$storedName = date('Ymd_His') . '_' . $safeName . '.' . $ext;
$destPath  = GX_UPLOAD_DIR . $storedName;

if (!move_uploaded_file($file['tmp_name'], $destPath)) {
    gx_json(false, 'Could not save the uploaded resume. Please try again.');
}

// ---- Build + send email with resume attached ----
$subject = 'New Job Application — ' . $name . ' (' . $profile . ')';
$body = '
<table style="font-family: Arial, sans-serif; font-size:14px; color:#111;" cellpadding="6">
  <tr><td><b>Full Name</b></td><td>' . gx_e($name) . '</td></tr>
  <tr><td><b>Phone</b></td><td>' . gx_e($phone) . '</td></tr>
  <tr><td><b>Applying Profile</b></td><td>' . gx_e($profile) . '</td></tr>
  <tr><td><b>Message</b></td><td>' . nl2br(gx_e($message)) . '</td></tr>
</table>';

$mail = new PHPMailer(true);
$sent = false;
try {
    $mail->SMTPDebug = 0;
    $mail->isSMTP();
    $mail->Host       = GX_SMTP_HOST;
    $mail->SMTPAuth   = true;
    $mail->Username   = GX_SMTP_USERNAME;
    $mail->Password   = GX_SMTP_PASSWORD;
    $mail->SMTPSecure = GX_SMTP_SECURE === 'ssl' ? PHPMailer::ENCRYPTION_SMTPS : PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = GX_SMTP_PORT;

    $mail->setFrom(GX_MAIL_FROM_EMAIL, GX_MAIL_FROM_NAME);
    $mail->addAddress(GX_APPLY_TO_EMAIL);
    $mail->addAttachment($destPath, $file['name']);

    $mail->isHTML(true);
    $mail->Subject = $subject;
    $mail->Body    = $body;

    $mail->send();
    $sent = true;
} catch (PHPMailerException $e) {
    error_log('Apply mail send failed: ' . $mail->ErrorInfo);
    $sent = false;
}

if ($sent) {
    gx_json(true, 'Thanks — your application has been submitted successfully.');
} else {
    gx_json(false, 'Something went wrong while submitting your application. Please try again later.');
}
