<?php
require_once '../config/connect.php';
require '../vendor/autoload.php';

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

$mail        = new PHPMailer(true);
$dateTimeNow = date('Y-m-d H:i:s');

$email = isset($_POST['email']) ? trim($_POST['email']) : "";

// ✅ Validate email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode([
        'status'  => 'error',
        'message' => '❌ Invalid email format.',
    ]);
    exit;
}

// ✅ Allow only specific domains
$allowedDomains = ["gmail.com", "yahoo.com", "outlook.com"];
$domain = substr(strrchr($email, "@"), 1);

if (!in_array($domain, $allowedDomains)) {
    echo json_encode([
        'status'  => 'error',
        'message' => 'Please enter a valid Email Address',
    ]);
    exit;
}

// ✅ Escape email for mysqli
$filteredEmail = mysqli_real_escape_string($mysqli_con, $email);

// ✅ Check if email already exists
$existsQry = "SELECT id FROM newsletter WHERE email = '$filteredEmail' LIMIT 1";
$existsRes = mysqli_query($mysqli_con, $existsQry);

if ($existsRes && mysqli_num_rows($existsRes) > 0) {
    echo json_encode([
        'status'  => 'error',
        'message' => ' Your email is already subscribed.',
    ]);
    exit;
}

// ✅ Insert using jRInsert (ADOdb helper you already have)
$data['email']      = $filteredEmail;
$data['created_at'] = $dateTimeNow;
$insertedid = jRInsert("newsletter", $data);

if ($insertedid > 0) {
    $_SESSION['success'] = 'Your message has been submitted successfully!';
    echo json_encode([
        'status'  => 'success',
        'message' => 'Message submitted successfully!',
    ]);
} else {
    $_SESSION['error'] = 'Something went wrong, please try again later.';
    echo json_encode([
        'status'  => 'error',
        'message' => 'Error in submitting your message.',
    ]);
}
