<?php

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

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require __DIR__ . '/PHPMailer/src/Exception.php';
require __DIR__ . '/PHPMailer/src/PHPMailer.php';
require __DIR__ . '/PHPMailer/src/SMTP.php';

$mail = new PHPMailer;

try {

    $name = $_POST['name'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $email = $_POST['email'] ?? '';
    $city = $_POST['city'] ?? '';
    $state = $_POST['state'] ?? '';
    $course = $_POST['course'] ?? '';

    $captchaInput = $_POST['captchaInput'] ?? '';
    $captchaCode = $_POST['captchaCode'] ?? '';

    $consent = $_POST['consent'] ?? '';

    /* =========================
       VALIDATION
    ========================= */

    if (
        empty($name) ||
        empty($phone) ||
        empty($email) ||
        empty($city)
    ) {

        echo json_encode([
            "status" => "error",
            "message" => "All fields are required"
        ]);

        exit();

    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

        echo json_encode([
            "status" => "error",
            "message" => "Invalid email format"
        ]);

        exit();

    }

    if (empty($consent)) {

        echo json_encode([
            "status" => "error",
            "message" => "Please accept the consent checkbox"
        ]);

        exit();

    }

    if (
        strtoupper(trim($captchaInput)) !==
        strtoupper(trim($captchaCode))
    ) {

        echo json_encode([
            "status" => "error",
            "message" => "CAPTCHA verification failed"
        ]);

        exit();

    }

    /* =========================
       MAIL CONFIG
    ========================= */

    $mail->isSMTP();

    $mail->Host = 'smtp.gmail.com';

    $mail->Port = 587;

    $mail->SMTPAuth = true;

    $mail->SMTPSecure = 'tls';

    $mail->Username = 'garimas876s@gmail.com';

    $mail->Password = 'ryib mmwa mzls pmts';

    $mail->setFrom(
        'hrbusiness424@gmail.com',
        'SKS'
    );

    $mail->addAddress(
        'hrbusiness424@gmail.com',
        'SKS'
    );

    $mail->isHTML(true);

    $mail->Subject =
        "New Admission Form: $name";

    $mail->Body = "

        <h2>New Admission Form Details</h2>

        <p><strong>Name:</strong> $name</p>

        <p><strong>Phone:</strong> $phone</p>

        <p><strong>Email:</strong> $email</p>

        <p><strong>City:</strong> $city</p>

        <p><strong>State:</strong> $state</p>

        <p><strong>Course:</strong> $course</p>

    ";

    $mail->send();

    echo json_encode([

        "status" => "success",

        "message" =>
            "Application submitted successfully"

    ]);

    exit();

} catch (Exception $e) {

    error_log(
        "Mailer Error: " . $mail->ErrorInfo
    );

    echo json_encode([

        "status" => "error",

        "message" =>
            "Unable to send enquiry right now"

    ]);

    exit();

}
?>