<?php
session_start();
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
header('Content-Type: application/json; charset=utf-8');


use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';


if(isset($_POST['user_id']) && isset($_POST['auth'])) {
    require 'config.php';
   
    $user_id = trim($_POST['user_id']);
    $auth = trim($_POST['auth']);

    $stmt = $con->prepare("SELECT * FROM users WHERE user_id = ? AND auth = ?");
    $stmt->bind_param("ss", $user_id, $auth);
    $stmt->execute();
    $result2 = $stmt->get_result();

    if ($result2->num_rows == 0) {
        echo json_encode(['status' => false, 'message' => 'User does not exist']);
        exit;
    }

    $rows = $result2->fetch_assoc();
    $email = $rows['email'];
    $firstname = $rows['firstname'];

    $code = random_int(1000, 9999);
    $code_expiry = date('Y-m-d H:i:s', strtotime('+10 minutes'));

    $stmt = $con->prepare("UPDATE users SET ver_code = ?, code_expiry = ? WHERE user_id = ? AND auth = ?");
    $stmt->bind_param("ssss", $code, $code_expiry, $user_id, $auth);
    $stmt->execute();

$subject = "Your Verification Code!";
$message = '<!DOCTYPE HTML>     
    <html>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
</head>
<body>
<div style="background-color:#eee; border:solid; border-width:thin; border-color:#EEE; position: relative; font-size:13px; padding-top:2em; padding:1em; font-family:Verdana, Geneva, sans-serif">
<div style="background-color:white; width: 80%; margin:auto; dborder:solid; dborder-width:thin; bdorder-color:#EEE; position: relative; font-size:13px; dtext-align: center; line-height: 20px; padding-top:2em; padding:1.5em; font-family:Verdana, Geneva, sans-serif">
<div style="width: 100%; text-align: center;">
</div>
<p>Dear '.$firstname.'</p>
<p>You just created an account on Eduabroad.</p>
<p>Your verification code is '.$code.'</p>
</div>
</div>

</body>
</html>';

    $mail = new PHPMailer();
    require 'mail_head.php';
    $mail->setFrom('dev@diimdevs.com', 'Eduabroad');
    $mail->addAddress($email);
    $mail->Subject = $subject;
    $mail->msgHTML($message);

    if ($mail->send()) {
        echo json_encode(['status' => true, 'message' => 'Verification code sent']);
    } else {
        error_log('Mail error: ' . $mail->ErrorInfo);
        echo json_encode(['status' => false, 'message' => 'Failed to send email']);
    }

    $stmt->close();
    $con->close();
}


?>