<?php
session_start();
require_once '../includes/db.php';
require_once '../includes/functions.php';
require_once '../includes/email_sender.php';

redirectIfNotAdmin();

$pending_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$step = isset($_GET['step']) ? intval($_GET['step']) : 1;

if (!$pending_id || !in_array($step, [1, 2, 3])) {
    header("Location: pending-transactions.php");
    exit();
}

// Fetch pending transaction
$stmt = $pdo->prepare("
    SELECT pt.*, u.full_name, u.email 
    FROM pending_transactions pt
    JOIN users u ON pt.user_id = u.user_id
    WHERE pt.pending_id = ?
");
$stmt->execute([$pending_id]);
$transaction = $stmt->fetch();

if (!$transaction) {
    header("Location: pending-transactions.php");
    exit();
}

// Get existing code or generate new one
if ($step == 1) $code = $transaction['sms_code_1'];
elseif ($step == 2) $code = $transaction['sms_code_2'];
else $code = $transaction['sms_code_3'];

if (!$code) {
    $code = sprintf("%06d", rand(0, 999999));
    if ($step == 1) {
        $updateStmt = $pdo->prepare("UPDATE pending_transactions SET sms_code_1 = ? WHERE pending_id = ?");
    } elseif ($step == 2) {
        $updateStmt = $pdo->prepare("UPDATE pending_transactions SET sms_code_2 = ? WHERE pending_id = ?");
    } else {
        $updateStmt = $pdo->prepare("UPDATE pending_transactions SET sms_code_3 = ? WHERE pending_id = ?");
    }
    $updateStmt->execute([$code, $pending_id]);
}

// Resend email
$emailSent = sendVerificationCode(
    $transaction['email'],
    $transaction['full_name'],
    $step,
    $code,
    $transaction['amount'],
    $pending_id
);

if ($emailSent) {
    $_SESSION['admin_success'] = "🔄 Code #$step resent successfully to {$transaction['email']}!";
} else {
    $_SESSION['admin_error'] = "❌ Failed to resend email. Please check your email configuration.";
}

header("Location: pending-transactions.php");
exit();
?>