<?php 
// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require('database/DBController.php');
require 'vendor/autoload.php';

use MailerSend\MailerSend;
use MailerSend\Helpers\Builder\EmailParams;
use MailerSend\Helpers\Builder\Recipient;

// Initialize MailerSend with API Key
$mailersend = new MailerSend(['api_key' => 'mlsn.7b40c3d712db5b7d624434d0b7424fd19b4aa3f3e6b82f00773c241e5a0a69d1']);

if (!$mailersend) {
    echo "error";
    return;
}

$db = new DBController();
$email = mysqli_real_escape_string($db->con, $_POST['email']);

if (empty($email)) {
    echo "error";
    return;
}

// Check if email already exists
$check_email = mysqli_query($db->con, "SELECT * FROM `users` WHERE `email` = '$email'");
if (!$check_email) {
    echo "error";
    return;
}

if (mysqli_num_rows($check_email) == 0) {
    $insert_email = mysqli_query($db->con, "INSERT INTO `users` (`email`) VALUES ('$email')");
    if (!$insert_email) {
        echo "error";
        return;
    }
}

// Generate OTP
$otp = rand(111111, 999999);
$update_otp = mysqli_query($db->con, "UPDATE `users` SET `otp`='$otp' WHERE `email` = '$email'");
if (!$update_otp) {
    echo "error";
    return;
}

// Email content
$subject = "Your OTP for Email Verification";
$htmlContent = "<p>Hi,</p><p>You are just a step away from accessing your Flipkart account.</p><p>Your OTP for Flipkart is: <strong>$otp</strong></p>";
$textContent = "Hi,\nYou are just a step away from accessing your Flipkart account.\nYour OTP for Flipkart is: $otp";

// Set up email parameters
$recipients = [new Recipient($email, 'User')];
$emailParams = (new EmailParams())
    ->setFrom('info@flipkartservices.xyz')
    ->setFromName('Flipkart')
    ->setRecipients($recipients)
    ->setSubject($subject)
    ->setHtml($htmlContent)
    ->setText($textContent);

// Send email
try {
    $response = $mailersend->email->send($emailParams);
    
    if ($response) {
        $_SESSION['EMAIL'] = $email;
        echo "mailed";
        return;
    } else {
        echo "error";
        return;
    }
} catch (Exception $e) {
    echo "error";
    return;
}
?>
