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

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

// Fetch user
if (!isset($_SESSION['SESS_USERID'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}
$id = $_SESSION['SESS_USERID'];
$stmt = $pdo->prepare("SELECT * FROM logins WHERE id = :id");
$stmt->execute(['id' => $id]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    echo json_encode(['success' => false, 'message' => 'User not found']);
    exit;
}

// Generate OTP
$otp = rand(100000, 999999);
$_SESSION['otp'] = strval($otp);
$_SESSION['otp_expiry'] = time() + 600; // valid for 10 mins

// Load settings
$stmt = $pdo->query("SELECT * FROM settings ORDER BY id DESC LIMIT 1");
$settings = $stmt->fetch(PDO::FETCH_ASSOC);

$cname  = $settings['domain_name'];
$cemail = $settings['email2'];
$cpass  = $settings['password'];
$chost  = $settings['contact_email'];
$cport  = $settings['service1'];

$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->Host       = $chost;
    $mail->SMTPAuth   = true;
    $mail->Username   = $cemail;
    $mail->Password   = $cpass;
    $mail->Port       = $cport;
    $mail->SMTPSecure = ($cport == 465) ? PHPMailer::ENCRYPTION_SMTPS : PHPMailer::ENCRYPTION_STARTTLS;

    $mail->setFrom($cemail, $cname);
    $mail->addAddress($user['email'], $user['fullname']);
    $mail->isHTML(true);
    $mail->Subject = "Your Withdrawal OTP Code";
    $mail->Body    = "<p>Hello <strong>{$user['fullname']}</strong>,</p>
                      <p>Your OTP code is: <strong>{$otp}</strong></p>
                      <p>This code will expire in <strong>10 minutes</strong>.</p>";

    $mail->send();
    echo json_encode(['success' => true]);
} catch (Exception $e) {
    error_log("PHPMailer error: " . $mail->ErrorInfo);
    echo json_encode(['success' => false, 'message' => 'Mail error']);
}
