<?php
session_start();

error_reporting(E_ALL);
ini_set('display_errors', 1);

// ==========================
// PHPMailer files
// ==========================
require __DIR__ . '/../phpmailer/PHPMailer.php';
require __DIR__ . '/../phpmailer/SMTP.php';
require __DIR__ . '/../phpmailer/Exception.php';

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

// ==========================
// Validate request
// ==========================
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_POST['email'])) {
    die("Invalid request");
}

$email = trim($_POST['email']);

// ==========================
// Generate OTP
// ==========================
$otp = random_int(100000, 999999);

// Store OTP in session
$_SESSION['reset_email'] = $email;
$_SESSION['reset_otp']   = $otp;
$_SESSION['otp_time']    = time();

// ==========================
// Mailer
// ==========================
$mail = new PHPMailer(true);


try {
    // ==========================
    // SMTP CONFIG (cPanel)
    // ==========================
    $mail->isSMTP();
    $mail->Host       = 'mail.starserver.in';   // ⚠️ verify in cPanel → Connect Devices
    $mail->SMTPAuth   = true;
    $mail->Username   = 'support@starserver.in';
    $mail->Password   = 'STARINFOLAB.IN';  // 🔴 EMAIL account password
    $mail->AuthType   = 'LOGIN';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    $mail->Port       = 465;

    // 🔍 Debug (enable only for testing)
    // $mail->SMTPDebug = 2;
    // $mail->Debugoutput = 'html';

    // ==========================
    // Email headers
    // ==========================
    $mail->CharSet = 'UTF-8';
    $mail->setFrom('support@starserver.in', 'Star Server');
    $mail->addAddress($email);

    // ==========================
    // Content
    // ==========================
    $mail->isHTML(true);
    $mail->Subject = 'Star Server - Password Reset OTP';

    $mail->Body = "
        <h3>Password Reset Request</h3>
        <p>Your OTP for password reset is:</p>
        <h2>{$otp}</h2>
        <p>This OTP is valid for <strong>5 minutes</strong>.</p>
        <p>If you did not request this, please ignore this email.</p>
        <br>
        <p>Regards,<br><strong>Star Server Team</strong></p>
    ";

    $mail->AltBody = "Your OTP is: {$otp}. Valid for 5 minutes.";

    // ==========================
    // Send
    // ==========================
    $mail->send();

    echo "OTP SENT SUCCESSFULLY";
    header("Location: forget_password.php?status=success");
    exit;

} catch (Exception $e) {
    echo "MAIL ERROR: " . $mail->ErrorInfo;
}
