<?php
// must be the very first PHP thing in the file (no BOM, no blank lines before)
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// autoload PHPMailer first (adjust path if composer files are elsewhere)
require __DIR__ . '/../vendor/autoload.php';

include __DIR__ . '/../db_connect.php';
session_start();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ../frontend/forgot-password.php');
    exit();
}

$email = mysqli_real_escape_string($conn, $_POST['email'] ?? '');

if (empty($email)) {
    echo "<script>alert('Please enter your email'); window.location.href='../frontend/forgot-password.php';</script>";
    exit();
}

$result = mysqli_query($conn, "SELECT * FROM users WHERE email='$email'");

if (mysqli_num_rows($result) === 0) {
    echo "<script>alert('Email not found'); window.location.href='../frontend/forgot-password.php';</script>";
    exit();
}

// generate OTP and save into session (or DB if preferred)
$otp = rand(100000, 999999);
$_SESSION['reset_email'] = $email;
$_SESSION['otp'] = $otp;
$_SESSION['otp_time'] = time(); // for expiry (optional)

$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;

    // <<< CHANGE THESE to your Gmail + app password >>>
    $mail->Username = 'benjamindanieljr11@gmail.com';
    $mail->Password = 'tvvvkzlylfgdmcys';
    // ----------------------------------------------------

    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;

    $mail->setFrom('yourgmail@gmail.com', 'CarConnect');
    $mail->addAddress($email);

    $mail->isHTML(true);
    $mail->Subject = 'Your CarConnect Password Reset OTP';
    $mail->Body    = "<p>Your OTP for password reset is: <b>$otp</b></p><p>This OTP is valid for 10 minutes.</p>";

    $mail->send();

    echo "<script>alert('OTP sent to your email'); window.location.href='../frontend/verify-otp.php';</script>";
    exit();
} catch (Exception $e) {
    // log $e->getMessage() if you want
    echo "<script>alert('Could not send email: " . addslashes($mail->ErrorInfo) . "'); window.location.href='../frontend/forgot-password.php';</script>";
    exit();
}
