<?php
require_once "../includes/db.php";
session_start();

// PHPMailer
require_once "../phpmailer/Exception.php";
require_once "../phpmailer/PHPMailer.php";
require_once "../phpmailer/SMTP.php";

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

if (!isset($_SESSION['order'])) {
    header("Location: index.php");
    exit;
}

$order = $_SESSION['order'];
$order_id = $order['order_id'] ?? 0;

/* UPDATE DB STATUS */
if ($order_id > 0) {
    mysqli_query(
        $conn,
        "UPDATE hosting_plans SET status='Paid' WHERE id='$order_id'"
    );
}

/* EMAIL BODY (SHORT MESSAGE) */
$message = "
<p>Hi {$order['name']},</p>

<p>Your payment has been received successfully ✅</p>

<p>
<strong>Plan:</strong> {$order['plan']}<br>
<strong>Domain:</strong> {$order['domain']}<br>
<strong>Amount:</strong> ₹ {$order['amount']}
</p>

<p>
Your hosting will be activated shortly.
Login credentials will be sent to this email.
</p>

<p>
Regards,<br>
<strong>Star Server Team</strong>
</p>
";

/* SMTP SEND */
$mail = new PHPMailer(true);

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

    // 🔴 CHANGE THESE TWO
    $mail->Username   = 'yourgmail@gmail.com';
    $mail->Password   = 'YOUR_APP_PASSWORD';

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

    $mail->setFrom('no-reply@starserver.in', 'Star Server');
    $mail->addAddress($order['email'], $order['name']);

    $mail->isHTML(true);
    $mail->Subject = 'Payment Received – Star Server';
    $mail->Body    = $message;

    $mail->send();

} catch (Exception $e) {
    error_log("Mail Error: " . $mail->ErrorInfo);
}

/* CLEAN SESSION */
unset($_SESSION['order']);

/* REDIRECT */
header("Location: thank-you.php");
exit;
