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

redirectIfNotAdmin();

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

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

// Fetch pending transaction
$stmt = $pdo->prepare("
    SELECT pt.*, u.full_name, u.email, a.account_id, a.balance 
    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 = ? AND pt.sms_step IN ('step3_verified', 'ready_for_admin')
");
$stmt->execute([$pending_id]);
$transaction = $stmt->fetch();

if (!$transaction) {
    $_SESSION['admin_error'] = "Transaction not found or not ready for approval";
    header("Location: pending-transactions.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $notes = $_POST['notes'] ?? '';

    try {
        $pdo->beginTransaction();

        // Check if user has sufficient balance
        if ($transaction['balance'] < $transaction['amount']) {
            throw new Exception("Insufficient balance. User has $" . number_format($transaction['balance'], 2));
        }

        // Update pending transaction status
        $updateStmt = $pdo->prepare("
            UPDATE pending_transactions 
            SET sms_step = 'approved', admin_approved_at = NOW(), admin_approved_by = ?, admin_notes = ?
            WHERE pending_id = ?
        ");
        $updateStmt->execute([$_SESSION['user_id'], $notes, $pending_id]);

        // Update account balance
        $newBalance = $transaction['balance'] - $transaction['amount'];
        $balanceStmt = $pdo->prepare("UPDATE accounts SET balance = ? WHERE account_id = ?");
        $balanceStmt->execute([$newBalance, $transaction['account_id']]);

        // Record transaction
        $transStmt = $pdo->prepare("
            INSERT INTO transactions (account_id, type, amount, description, created_at) 
            VALUES (?, 'withdrawal', ?, ?, NOW())
        ");
        $transStmt->execute([$transaction['account_id'], $transaction['amount'], "Withdrawal approved by admin - " . ($notes ?: "Processed")]);

        // Send email notification
        $subject = "Withdrawal Approved - Oakshire Finance";
        $message = "
            <html>
            <body style='font-family: Arial, sans-serif;'>
                <h2 style='color: #0a2540;'>Withdrawal Approved</h2>
                <p>Dear <strong>" . htmlspecialchars($transaction['full_name']) . "</strong>,</p>
                <p>Your withdrawal request has been <strong>APPROVED</strong> and processed.</p>
                <p><strong>Amount:</strong> $" . number_format($transaction['amount'], 2) . "</p>
                <p><strong>New Balance:</strong> $" . number_format($newBalance, 2) . "</p>
                <p><strong>Reference:</strong> #" . $pending_id . "</p>
                " . ($notes ? "<p><strong>Admin Notes:</strong> " . htmlspecialchars($notes) . "</p>" : "") . "
                <br>
                <p>Thank you for banking with Oakshire Finance!</p>
            </body>
            </html>
        ";

        sendNotification($transaction['email'], $subject, $message);

        $pdo->commit();

        $_SESSION['admin_success'] = "Withdrawal of $" . number_format($transaction['amount'], 2) . " approved and processed!";
        header("Location: pending-transactions.php");
        exit();

    } catch (Exception $e) {
        $pdo->rollBack();
        $error = $e->getMessage();
    }
}

// Get admin info
$adminStmt = $pdo->prepare("SELECT full_name FROM users WHERE user_id = ?");
$adminStmt->execute([$_SESSION['user_id']]);
$admin = $adminStmt->fetch();
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>Approve Withdrawal - Oakshire Finance Admin</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;400;500;600;700;800&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: #f8f9fc;
        }

        .dashboard-wrapper {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 280px;
            background: white;
            border-right: 1px solid #e9ecef;
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            overflow-y: auto;
            transition: transform 0.3s ease;
            z-index: 100;
        }

        .sidebar-header {
            padding: 24px;
            text-align: center;
            border-bottom: 1px solid #e9ecef;
        }

        .logo {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            text-decoration: none;
        }

        .logo-icon {
            width: 40px;
            height: 40px;
            background: #0a2540;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .logo-icon i {
            color: white;
            font-size: 20px;
        }

        .logo-text {
            font-size: 22px;
            font-weight: 700;
            color: #0a2540;
        }

        .nav-menu {
            padding: 24px 16px;
        }

        .nav-link {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: #495057;
            transition: all 0.3s;
            font-weight: 500;
        }

        .nav-link:hover {
            background: #f1f3f9;
            color: #1a4d8c;
        }

        .nav-link.active {
            background: #0a2540;
            color: white;
        }

        .main-content {
            flex: 1;
            margin-left: 280px;
            min-height: 100vh;
        }

        .top-header {
            background: white;
            border-bottom: 1px solid #e9ecef;
            padding: 16px 32px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 99;
        }

        .page-title h1 {
            font-size: 24px;
            font-weight: 700;
            color: #212529;
        }

        .content-area {
            padding: 32px;
        }

        .card {
            background: white;
            border-radius: 24px;
            border: 1px solid #e9ecef;
            padding: 32px;
            max-width: 600px;
            margin: 0 auto;
        }

        .card h2 {
            font-size: 22px;
            font-weight: 700;
            margin-bottom: 24px;
            color: #0a2540;
        }

        .info-box {
            background: #f8f9fc;
            padding: 20px;
            border-radius: 16px;
            margin-bottom: 24px;
        }

        .info-box p {
            margin: 8px 0;
            font-size: 14px;
        }

        .info-box strong {
            color: #0a2540;
        }

        .warning-box {
            background: rgba(220, 53, 69, 0.05);
            border: 1px solid #dc3545;
            padding: 16px;
            border-radius: 12px;
            margin-bottom: 24px;
        }

        .warning-box p {
            color: #dc3545;
            font-size: 13px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            font-size: 13px;
            font-weight: 500;
            color: #495057;
            margin-bottom: 8px;
        }

        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 12px 16px;
            border: 1.5px solid #e9ecef;
            border-radius: 12px;
            font-size: 14px;
            transition: all 0.3s;
        }

        .form-group input:focus,
        .form-group textarea:focus {
            border-color: #1a4d8c;
            outline: none;
        }

        .btn-success {
            width: 100%;
            padding: 14px;
            background: #2e7d32;
            color: white;
            border: none;
            border-radius: 12px;
            font-weight: 600;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-success:hover {
            background: #1b5e20;
            transform: translateY(-2px);
        }

        .btn-danger {
            width: 100%;
            padding: 14px;
            background: #dc3545;
            color: white;
            border: none;
            border-radius: 12px;
            font-weight: 600;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s;
            margin-top: 12px;
        }

        .btn-danger:hover {
            background: #c82333;
            transform: translateY(-2px);
        }

        .btn-secondary {
            display: inline-block;
            padding: 10px 20px;
            background: #e9ecef;
            color: #495057;
            text-decoration: none;
            border-radius: 10px;
            font-size: 14px;
            margin-top: 16px;
            text-align: center;
        }

        .alert-danger {
            padding: 14px 16px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
            background: rgba(220, 53, 69, 0.1);
            border-left: 3px solid #dc3545;
            color: #dc3545;
        }

        .hamburger {
            display: none;
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
        }

        @media (max-width: 1024px) {
            .sidebar {
                transform: translateX(-100%);
                z-index: 1000;
            }

            .sidebar.mobile-open {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0;
            }

            .hamburger {
                display: block;
            }
        }

        @media (max-width: 768px) {
            .content-area {
                padding: 20px;
            }

            .top-header {
                padding: 12px 20px;
            }

            .page-title h1 {
                font-size: 20px;
            }

            .card {
                padding: 20px;
            }
        }
    </style>
    <link rel="stylesheet" href="../assets/css/nexus-theme.css">
</head>

<body>
    <div class="dashboard-wrapper">
        <aside class="sidebar" id="sidebar">
            <div class="sidebar-header">
                <a href="dashboard.php" class="logo">
                    <div class="logo-icon"><i class="fas fa-building-columns"></i></div>
                    <span class="logo-text">Oakshire Finance</span>
                </a>
            </div>
            <nav class="nav-menu">
                <a href="dashboard.php" class="nav-link"><i class="fas fa-chart-line"></i> Dashboard</a>
                <a href="manage-users.php" class="nav-link"><i class="fas fa-users"></i> Manage Users</a>
                <a href="pending-transactions.php" class="nav-link active"><i class="fas fa-clock"></i> Pending
                    Transactions</a>
            </nav>
        </aside>

        <main class="main-content">
            <header class="top-header">
                <button class="hamburger" id="hamburger"><i class="fas fa-bars"></i></button>
                <div class="page-title">
                    <h1>Approve Withdrawal</h1>
                </div>
            </header>

            <div class="content-area">
                <?php if (isset($error)): ?>
                    <div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> <?= $error ?></div>
                <?php endif; ?>

                <div class="card">
                    <h2><i class="fas fa-check-circle"></i> Confirm Approval</h2>

                    <div class="info-box">
                        <p><strong>Transaction Details:</strong></p>
                        <p>User: <?= htmlspecialchars($transaction['full_name']) ?></p>
                        <p>Email: <?= htmlspecialchars($transaction['email']) ?></p>
                        <p>Amount: <strong
                                style="color: #dc3545;">$<?= number_format($transaction['amount'], 2) ?></strong></p>
                        <p>Current Balance: $<?= number_format($transaction['balance'], 2) ?></p>
                        <p>New Balance After: <strong
                                style="color: #2e7d32;">$<?= number_format($transaction['balance'] - $transaction['amount'], 2) ?></strong>
                        </p>
                    </div>

                    <div class="warning-box">
                        <p><i class="fas fa-exclamation-triangle"></i> By approving this withdrawal, the user's account
                            will be debited and the user will receive an email confirmation.</p>
                    </div>

                    <form method="POST">
                        <div class="form-group">
                            <label>Admin Notes (Optional)</label>
                            <textarea name="notes" rows="3"
                                placeholder="Add any notes about this approval..."></textarea>
                        </div>

                        <button type="submit" class="btn-success">
                            <i class="fas fa-check-circle"></i> Confirm & Approve Withdrawal
                        </button>

                        <a href="pending-transactions.php" class="btn-secondary"
                            style="display: block; text-align: center;">
                            <i class="fas fa-arrow-left"></i> Back to Pending List
                        </a>
                    </form>
                </div>
            </div>
        </main>
    </div>

    <script>
        const hamburger = document.getElementById('hamburger');
        const sidebar = document.getElementById('sidebar');
        if (hamburger) hamburger.addEventListener('click', () => sidebar.classList.toggle('mobile-open'));
    </script>
</body>

</html>