<?php
require_once __DIR__ . '/db/config.php';
require_once __DIR__ . '/mail/MailService.php';

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

$response = ['success' => false, 'message' => 'An unknown error occurred.'];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response['message'] = 'Invalid request method.';
    echo json_encode($response);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);

if (empty($data)) {
    $response['message'] = 'No data received.';
    echo json_encode($response);
    exit;
}

// Sanitize and validate data
$companyName = htmlspecialchars($data['companyName'] ?? '');
$yourName = htmlspecialchars($data['yourName'] ?? '');
$workEmail = filter_var($data['workEmail'] ?? '', FILTER_SANITIZE_EMAIL);
$role = htmlspecialchars($data['role'] ?? '');
$employees = filter_var($data['employees'] ?? '', FILTER_SANITIZE_NUMBER_INT);
$rolesPerMonth = filter_var($data['rolesPerMonth'] ?? '', FILTER_SANITIZE_NUMBER_INT);
$candidatesPerRole = filter_var($data['candidatesPerRole'] ?? '', FILTER_SANITIZE_NUMBER_INT);
$ats = htmlspecialchars($data['ats'] ?? '');
$scheduling = htmlspecialchars($data['scheduling'] ?? '');
$painPoints = htmlspecialchars($data['painPoints'] ?? '');
$successMetrics = htmlspecialchars($data['successMetrics'] ?? '');
$hiringFocus = htmlspecialchars($data['hiringFocus'] ?? '');

if (!filter_var($workEmail, FILTER_VALIDATE_EMAIL)) {
    $response['message'] = 'Invalid email address.';
    echo json_encode($response);
    exit;
}

if (empty($companyName) || empty($yourName)) {
    $response['message'] = 'Please fill out all required fields.';
    echo json_encode($response);
    exit;
}

// Insert into database
$pdo = db();
$stmt = $pdo->prepare("
    INSERT INTO applications (name, company, email, role, employees, roles_per_month, candidates_per_role, ats, scheduling, pain_points, success_metrics, hiring_focus)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");

try {
    $stmt->execute([
        $yourName,
        $companyName,
        $workEmail,
        $role,
        $employees,
        $rolesPerMonth,
        $candidatesPerRole,
        $ats,
        $scheduling,
        $painPoints,
        $successMetrics,
        $hiringFocus
    ]);
} catch (PDOException $e) {
    error_log('Database Error: ' . $e->getMessage());
    $response['message'] = 'There was an error saving your application. Please try again later.';
    echo json_encode($response);
    exit;
}

$to = getenv('MAIL_TO');
$subject = 'New FinMox Beta Application';

$htmlBody = ""
    . "<h1>New FinMox Beta Application</h1>"
    . "<p><strong>Company Name:</strong> {$companyName}</p>"
    . "<p><strong>Name:</strong> {$yourName}</p>"
    . "<p><strong>Email:</strong> {$workEmail}</p>"
    . "<p><strong>Role:</strong> {$role}</p>"
    . "<p><strong>Employees:</strong> {$employees}</p>"
    . "<p><strong>Roles Per Month:</strong> {$rolesPerMonth}</p>"
    . "<p><strong>Candidates Per Role:</strong> {$candidatesPerRole}</p>"
    . "<p><strong>ATS:</strong> {$ats}</p>"
    . "<p><strong>Scheduling:</strong> {$scheduling}</p>"
    . "<p><strong>Pain Points:</strong> {$painPoints}</p>"
    . "<p><strong>Success Metrics:</strong> {$successMetrics}</p>"
    . "<p><strong>Hiring Focus:</strong> {$hiringFocus}</p>";

$res = MailService::sendMail($to, $subject, $htmlBody);

if (!empty($res['success'])) {
    $response['success'] = true;
    $response['message'] = 'Application submitted successfully!';
} else {
    error_log('MailService Error: ' . ($res['error'] ?? 'Unknown error'));
    $response['message'] = 'There was an error submitting your application. Please try again later.';
}

echo json_encode($response);
