<?php
session_start();
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
require 'PHPMailer/src/Exception.php';

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

$identifier = $_POST['identifier'] ?? '';
$identifier = trim($identifier);
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: login.html");
    exit();
}
if (empty($identifier)) {
    die("Username or Email required.");
}


try {
    require_once 'connection.php';

    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :id OR email = :id2");
    $stmt->bindParam(':id', $identifier);
    $stmt->bindParam(':id2', $identifier);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    $_SESSION['username'] = $user['username'];

    if (!$user) {
        $_SESSION['error_message'] = "No account found !!";
        header("Location: forgot_password.php");
        exit();
    }

    $otp = random_int(100000, 999999);
    $_SESSION['reset_userid'] = $user['userid'];
    $_SESSION['reset_email'] = $user['email'];
    $_SESSION['reset_otp'] = $otp;

    $mail = new PHPMailer(true);
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'abhinavjindal19here@gmail.com';
    $mail->Password = 'wlhz lvsb ifcu qnhq';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    $mail->setFrom('abhinavjindal19here@gmail.com', 'Password Recovery');
    $mail->isHTML(false);
    $mail->addAddress($user['email']);
    $mail->Subject = 'Your OTP Code';
    $mail->Body = "Your OTP is: $otp\nThis OTP is valid for 5 minutes.";

    $mail->send();
    header("Location: verify_otp.php");
    exit();
} catch (Exception $e) {
    die("Error sending email: {$mail->ErrorInfo}");
} catch (PDOException $e) {
    die("DB Error: " . $e->getMessage());
}
