<?php
/**
 * submit.php — JP Investment Real Estate Group Job Portal
 * Place this file in the same folder as job-portal.html on the server.
 * Requires PHP 7.4+ (standard on all cPanel hosting).
 */

// Always return JSON
header('Content-Type: application/json');

// ============================================================
// CONFIGURATION — EDIT THESE VALUES BEFORE UPLOADING
// ============================================================

$TURNSTILE_SECRET = '0x4AAAAAADq5cyaN5to58rq9AWAJCxGnPb0';  // From Cloudflare dashboard
$CAREERS_EMAIL    = 'careers@jpinvestmentrealestate.com';
$SMTP_FROM        = 'careers@jpinvestmentrealestate.com'; // Must match cPanel email

// ============================================================
// STEP 1 — VERIFY CLOUDFLARE TURNSTILE (bot protection)
// ============================================================

$token = trim($_POST['cf-turnstile-response'] ?? '');

if (empty($token)) {
    echo json_encode(['success' => false, 'message' => 'Security check missing. Please complete the verification widget and try again.']);
    exit;
}

$verifyContext = stream_context_create([
    'http' => [
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => http_build_query([
            'secret'   => $TURNSTILE_SECRET,
            'response' => $token,
            'remoteip' => $_SERVER['REMOTE_ADDR'] ?? ''
        ])
    ]
]);

$verifyResponse = @file_get_contents(
    'https://challenges.cloudflare.com/turnstile/v0/siteverify',
    false,
    $verifyContext
);

if ($verifyResponse === false) {
    echo json_encode(['success' => false, 'message' => 'Could not reach security verification server. Please try again.']);
    exit;
}

$verifyResult = json_decode($verifyResponse, true);

if (empty($verifyResult['success'])) {
    echo json_encode(['success' => false, 'message' => 'Security verification failed. Please refresh the page and try again.']);
    exit;
}

// ============================================================
// STEP 2 — HONEYPOT CHECK (catches basic bots)
// ============================================================

if (!empty($_POST['website'])) {
    // Bot detected — silently pretend success so bots don't retry
    echo json_encode(['success' => true]);
    exit;
}

// ============================================================
// STEP 3 — COLLECT AND SANITIZE FORM DATA
// ============================================================

function clean($value) {
    return htmlspecialchars(strip_tags(trim($value ?? '')), ENT_QUOTES, 'UTF-8');
}

$role             = clean($_POST['role']             ?? '');
$first_name       = clean($_POST['first_name']       ?? '');
$last_name        = clean($_POST['last_name']        ?? '');
$email            = filter_var(trim($_POST['email'] ?? ''), FILTER_SANITIZE_EMAIL);
$phone            = clean($_POST['phone']            ?? '');
$address          = clean($_POST['address']          ?? '');
$city             = clean($_POST['city']             ?? '');
$state_zip        = clean($_POST['state_zip']        ?? '');
$linkedin         = clean($_POST['linkedin']         ?? '');
$experience       = clean($_POST['experience']       ?? '');
$education        = clean($_POST['education']        ?? '');
$availability     = clean($_POST['availability']     ?? '');
$personal_statement = clean($_POST['personal_statement'] ?? '');
$q1               = clean($_POST['q1']               ?? '');
$q2               = clean($_POST['q2']               ?? '');
$q3               = clean($_POST['q3']               ?? '');
$q4               = clean($_POST['q4']               ?? '');
$q5               = clean($_POST['q5']               ?? '');
$q6               = clean($_POST['q6']               ?? '');
$q7               = clean($_POST['q7']               ?? '');
$q8               = clean($_POST['q8']               ?? '');
$ip               = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$submitted_at     = date('Y-m-d H:i:s T');

// Validate required fields server-side
if (empty($role) || empty($first_name) || empty($last_name) || empty($email) || empty($phone)) {
    echo json_encode(['success' => false, 'message' => 'Required fields are missing. Please complete the form.']);
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['success' => false, 'message' => 'Please enter a valid email address.']);
    exit;
}

// ============================================================
// STEP 4 — SAVE APPLICATION AS BACKUP FILE
// ============================================================

$saveDir = __DIR__ . '/submissions/';

if (!is_dir($saveDir)) {
    mkdir($saveDir, 0750, true);
}

// File name: date + applicant name (safe characters only)
$safeName = preg_replace('/[^a-zA-Z0-9_-]/', '_', $first_name . '_' . $last_name);
$filename = $saveDir . date('Y-m-d_H-i-s') . '_' . $safeName . '.txt';

$fileContent = <<<EOT
=======================================================
 JP INVESTMENT REAL ESTATE GROUP — JOB APPLICATION
=======================================================
Submitted:   $submitted_at
IP Address:  $ip

POSITION APPLIED FOR
---------------------
Role:        $role

PERSONAL INFORMATION
---------------------
Name:        $first_name $last_name
Email:       $email
Phone:       $phone
Address:     $address
City:        $city
State/ZIP:   $state_zip
LinkedIn:    $linkedin

BACKGROUND
---------------------
Experience:  $experience
Education:   $education
Available:   $availability

PERSONAL STATEMENT
---------------------
$personal_statement

INTERVIEW RESPONSES
---------------------
Q1 — Why JP Investment / Knowledge of CRE:
$q1

Q2 — Managing multiple priorities under pressure:
$q2

Q3 — Unique skills and qualifications:
$q3

Q4 — Teamwork example:
$q4

Q5 — 3–5 year professional vision:
$q5

Q6 — Handling feedback and criticism:
$q6

Q7 — Greatest professional achievement:
$q7

Q8 — Additional information (optional):
$q8

=======================================================
EOT;

file_put_contents($filename, $fileContent);

// ============================================================
// STEP 5 — SEND EMAIL VIA SERVER MAIL
// ============================================================

$subject = "New Job Application — $role — $first_name $last_name";

$emailBody = $fileContent; // Reuse the same formatted content

$headers  = "From: $SMTP_FROM\r\n";
$headers .= "Reply-To: $email\r\n";
$headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

$mailSent = mail($CAREERS_EMAIL, $subject, $emailBody, $headers);

// Even if mail() fails, the file backup exists — we still return success
// to avoid confusing the applicant. You can check /submissions/ manually.

// ============================================================
// STEP 6 — RETURN SUCCESS RESPONSE
// ============================================================

echo json_encode(['success' => true]);
exit;
