<?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 details
$stmt = $pdo->prepare("
    SELECT pt.*, u.full_name, u.email, a.account_number 
    FROM pending_transactions pt
    JOIN users u ON pt.user_id = u.user_id
    JOIN accounts a ON pt.account_id = a.account_id
    WHERE pt.pending_id = ?
");
$stmt->execute([$pending_id]);
$transaction = $stmt->fetch();

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

// Check if step is correct
if ($step == 1 && $transaction['sms_step'] != 'step1_pending') {
    $_SESSION['admin_error'] = "Invalid step. Current status: " . $transaction['sms_step'];
    header("Location: pending-transactions.php");
    exit();
}
if ($step == 2 && $transaction['sms_step'] != 'step1_verified') {
    $_SESSION['admin_error'] = "Please complete Step 1 first";
    header("Location: pending-transactions.php");
    exit();
}
if ($step == 3 && $transaction['sms_step'] != 'step2_verified') {
    $_SESSION['admin_error'] = "Please complete Step 2 first";
    header("Location: pending-transactions.php");
    exit();
}

// Generate 6-digit code
$code = sprintf("%06d", rand(0, 999999));

// Send email using your working email sender
$emailSent = sendVerificationCode(
    $transaction['email'],
    $transaction['full_name'],
    $step,
    $code,
    $transaction['amount'],
    $pending_id
);

if ($emailSent) {
    // Determine which column to update
    if ($step == 1) {
        $code_column = 'sms_code_1';
        $sent_column = 'sms1_sent_at';
        $new_step = 'step1_sent';
    } elseif ($step == 2) {
        $code_column = 'sms_code_2';
        $sent_column = 'sms2_sent_at';
        $new_step = 'step2_sent';
    } else {
        $code_column = 'sms_code_3';
        $sent_column = 'sms3_sent_at';
        $new_step = 'step3_sent';
    }
    
    // Update database with code
    $updateStmt = $pdo->prepare("
        UPDATE pending_transactions 
        SET $code_column = ?, sms_step = ?, $sent_column = NOW() 
        WHERE pending_id = ?
    ");
    $updateStmt->execute([$code, $new_step, $pending_id]);
    
    // Log admin action
    $logStmt = $pdo->prepare("
        INSERT INTO sms_admin_logs (pending_id, admin_id, user_id, phone_number, sms_step, sms_code, status) 
        VALUES (?, ?, ?, ?, ?, ?, 'sent')
    ");
    $logStmt->execute([$pending_id, $_SESSION['user_id'], $transaction['user_id'], $transaction['email'], $step, $code]);
    
    $_SESSION['admin_success'] = "✅ Code #$step sent successfully to {$transaction['email']}! Code: $code";
} else {
    $_SESSION['admin_error'] = "❌ Failed to send email. Please check your email configuration.";
}

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