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

redirectIfNotAdmin();

$error = '';
$success = '';
$users = [];

// Fetch all users with accounts
$usersStmt = $pdo->query("
    SELECT u.user_id, u.full_name, u.email, a.account_id, a.account_number, a.balance 
    FROM users u 
    LEFT JOIN accounts a ON u.user_id = a.user_id 
    ORDER BY u.created_at DESC
");
$users = $usersStmt->fetchAll();

// Handle balance adjustment
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $userId = intval($_POST['user_id']);
    $amount = floatval($_POST['amount']);
    $action = $_POST['balance_action'];
    $description = trim($_POST['description'] ?? 'Admin adjustment');

    if ($amount <= 0) {
        $error = "Amount must be greater than 0.";
    } else {
        // Get user account
        $stmt = $pdo->prepare("SELECT account_id, balance FROM accounts WHERE user_id = ?");
        $stmt->execute([$userId]);
        $account = $stmt->fetch();

        if (!$account) {
            $error = "User account not found.";
        } else {
            try {
                $pdo->beginTransaction();

                if ($action === 'add') {
                    $newBalance = $account['balance'] + $amount;
                    $transactionType = 'deposit';
                    $transactionDesc = "Admin added $" . number_format($amount, 2) . " - $description";
                    $actionText = "added";
                } elseif ($action === 'deduct') {
                    if ($amount > $account['balance']) {
                        throw new Exception("Insufficient balance. User has $" . number_format($account['balance'], 2));
                    }
                    $newBalance = $account['balance'] - $amount;
                    $transactionType = 'withdrawal';
                    $transactionDesc = "Admin deducted $" . number_format($amount, 2) . " - $description";
                    $actionText = "deducted";
                } else {
                    throw new Exception("Invalid action.");
                }

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

                // Record transaction
                $stmt = $pdo->prepare("INSERT INTO transactions (account_id, type, amount, description, created_at) VALUES (?, ?, ?, ?, NOW())");
                $stmt->execute([$account['account_id'], $transactionType, $amount, $transactionDesc]);

                // Send email notification
                $userStmt = $pdo->prepare("SELECT email, full_name FROM users WHERE user_id = ?");
                $userStmt->execute([$userId]);
                $user = $userStmt->fetch();

                $subject = "Account Balance Updated - Oakshire Finance";
                $message = "
                    <html>
                    <body style='font-family: Arial, sans-serif;'>
                        <h2 style='color: #0a2540;'>Account Balance Update</h2>
                        <p>Dear <strong>" . htmlspecialchars($user['full_name']) . "</strong>,</p>
                        <p>Your account balance has been updated by an administrator.</p>
                        <p><strong>Action:</strong> $" . number_format($amount, 2) . " " . $actionText . "</p>
                        <p><strong>Previous Balance:</strong> $" . number_format($account['balance'], 2) . "</p>
                        <p><strong>New Balance:</strong> $" . number_format($newBalance, 2) . "</p>
                        <p><strong>Reference:</strong> $description</p>
                        <p>If you have any questions, please contact our support team.</p>
                        <br>
                        <p>Best regards,<br>Oakshire Finance Team</p>
                    </body>
                    </html>
                ";

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

                $pdo->commit();
                $success = "$" . number_format($amount, 2) . " successfully " . $actionText . " to user's account.";

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

// Get admin info for sidebar
$adminId = $_SESSION['user_id'];
$adminInfo = $pdo->prepare("SELECT full_name, email FROM users WHERE user_id = ?");
$adminInfo->execute([$adminId]);
$admin = $adminInfo->fetch();
?>

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage User Balance - Oakshire Finance Admin</title>
    <link
        href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;14..32,400;14..32,500;14..32,600;14..32,700;14..32,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;
        }

        :root {
            --primary-navy: #0a2540;
            --primary-dark: #0a1c2f;
            --primary-blue: #1a4d8c;
            --success-green: #2e7d32;
            --error-red: #dc3545;
            --gray-50: #f8f9fc;
            --gray-100: #f1f3f9;
            --gray-200: #e9ecef;
            --gray-300: #dee2e6;
            --gray-600: #6c757d;
            --gray-700: #495057;
            --gray-800: #343a40;
            --gray-900: #212529;
            --white: #ffffff;
            --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.08);
            --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.05);
            --shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.08);
            --transition: all 0.3s ease;
        }

        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: var(--gray-50);
            color: var(--gray-800);
        }

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

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

        .sidebar-header {
            padding: 24px;
            border-bottom: 1px solid var(--gray-200);
            text-align: center;
        }

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

        .logo-icon {
            width: 40px;
            height: 40px;
            background: var(--primary-navy);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

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

        .logo-text {
            font-size: 22px;
            font-weight: 700;
            color: var(--primary-navy);
        }

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

        .nav-item {
            margin-bottom: 4px;
        }

        .nav-link {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: var(--gray-700);
            transition: var(--transition);
            font-weight: 500;
            font-size: 14px;
        }

        .nav-link i {
            width: 20px;
            font-size: 18px;
        }

        .nav-link:hover {
            background: var(--gray-100);
            color: var(--primary-blue);
        }

        .nav-link.active {
            background: var(--primary-navy);
            color: white;
        }

        .logout-section {
            padding: 16px;
            border-top: 1px solid var(--gray-200);
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: var(--white);
        }

        .logout-btn {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: var(--error-red);
            font-weight: 500;
        }

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

        .top-header {
            background: var(--white);
            border-bottom: 1px solid var(--gray-200);
            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: var(--gray-900);
        }

        .user-menu {
            display: flex;
            align-items: center;
            gap: 24px;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, var(--primary-navy), var(--primary-blue));
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .user-avatar i {
            font-size: 18px;
            color: white;
        }

        .content-area {
            padding: 32px;
        }

        .card {
            background: var(--white);
            border-radius: 24px;
            border: 1px solid var(--gray-200);
            padding: 24px;
            margin-bottom: 24px;
        }

        .card h2 {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 20px;
        }

        .alert {
            padding: 14px 16px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .alert-success {
            background: rgba(46, 125, 50, 0.1);
            border-left: 3px solid var(--success-green);
            color: var(--success-green);
        }

        .alert-danger {
            background: rgba(220, 53, 69, 0.1);
            border-left: 3px solid var(--error-red);
            color: var(--error-red);
        }

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

        .form-group label {
            display: block;
            font-size: 13px;
            font-weight: 500;
            color: var(--gray-700);
            margin-bottom: 8px;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 12px 16px;
            font-size: 14px;
            border: 1.5px solid var(--gray-200);
            border-radius: 12px;
            transition: var(--transition);
            outline: none;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            border-color: var(--primary-blue);
            box-shadow: 0 0 0 3px rgba(26, 77, 140, 0.1);
        }

        .btn-primary {
            padding: 12px 24px;
            background: var(--primary-navy);
            color: white;
            border: none;
            border-radius: 12px;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
        }

        .btn-primary:hover {
            background: var(--primary-dark);
            transform: translateY(-1px);
        }

        .table-container {
            background: var(--white);
            border-radius: 20px;
            border: 1px solid var(--gray-200);
            overflow-x: auto;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            min-width: 600px;
        }

        .data-table th,
        .data-table td {
            padding: 16px 20px;
            text-align: left;
            border-bottom: 1px solid var(--gray-200);
        }

        .data-table th {
            background: var(--gray-50);
            font-weight: 600;
            font-size: 12px;
            color: var(--gray-700);
            text-transform: uppercase;
        }

        .data-table td {
            font-size: 13px;
        }

        .badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
        }

        .badge-active {
            background: rgba(46, 125, 50, 0.1);
            color: var(--success-green);
        }

        .btn-sm {
            padding: 4px 12px;
            font-size: 12px;
            border-radius: 8px;
            background: var(--primary-blue);
            color: white;
            text-decoration: none;
            display: inline-block;
        }

        .btn-sm:hover {
            background: var(--primary-dark);
        }

        .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;
            }
        }
    </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">
                <div class="nav-item"><a href="dashboard.php" class="nav-link"><i class="fas fa-chart-line"></i>
                        Dashboard</a></div>
                <div class="nav-item"><a href="manage-users.php" class="nav-link"><i class="fas fa-users"></i> Manage
                        Users</a></div>
                <div class="nav-item"><a href="manage-balance.php" class="nav-link active"><i class="fas fa-wallet"></i>
                        Manage Balance</a></div>
                <div class="nav-item"><a href="manage-loans.php" class="nav-link"><i
                            class="fas fa-hand-holding-usd"></i> Manage Loans</a></div>
                <div class="nav-item"><a href="manage-investments.php" class="nav-link"><i class="fas fa-chart-pie"></i>
                        Manage Investments</a></div>
                <div class="nav-item"><a href="track-investments.php" class="nav-link"><i
                            class="fas fa-chart-simple"></i> Users Investments</a></div>
                <div class="nav-item"><a href="role.php" class="nav-link"><i class="fas fa-user-tag"></i> Roles</a>
                </div>
                <div class="nav-item"><a href="recent_transactions.php" class="nav-link"><i
                            class="fas fa-exchange-alt"></i> Transactions</a></div>
                <div class="nav-item"><a href="loan-history.php" class="nav-link"><i class="fas fa-history"></i> Loan
                        History</a></div>
                <div class="nav-item"><a href="login-records.php" class="nav-link"><i class="fas fa-sign-in-alt"></i>
                        Login Records</a></div>
                <div class="nav-item"><a href="manage-messages.php" class="nav-link"><i class="fas fa-envelope"></i>
                        Messages</a></div>
            </nav>
            <div class="logout-section">
                <a href="../logout.php" class="logout-btn"><i class="fas fa-sign-out-alt"></i> Logout</a>
            </div>
        </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>Manage User Balance</h1>
                </div>
                <div class="user-menu">
                    <div class="user-avatar"><i class="fas fa-user-shield"></i></div>
                </div>
            </header>

            <div class="content-area">
                <?php if ($success): ?>
                    <div class="alert alert-success"><i class="fas fa-check-circle"></i> <?= $success ?></div>
                <?php endif; ?>
                <?php if ($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-money-bill-wave"></i> Add or Deduct Money</h2>
                    <form method="POST">
                        <div class="form-group">
                            <label>Select User</label>
                            <select name="user_id" required>
                                <option value="">-- Select User --</option>
                                <?php foreach ($users as $user): ?>
                                    <option value="<?= $user['user_id'] ?>">
                                        <?= htmlspecialchars($user['full_name']) ?> - <?= $user['account_number'] ?>
                                        ($<?= number_format($user['balance'], 2) ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Action</label>
                            <select name="balance_action" required>
                                <option value="add">Add Money (+)</option>
                                <option value="deduct">Deduct Money (-)</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Amount ($)</label>
                            <input type="number" name="amount" step="0.01" min="0.01" required>
                        </div>
                        <div class="form-group">
                            <label>Description/Reference</label>
                            <textarea name="description" rows="2"
                                placeholder="Reason for this adjustment..."></textarea>
                        </div>
                        <button type="submit" name="action" value="update" class="btn-primary"><i
                                class="fas fa-save"></i> Update Balance</button>
                    </form>
                </div>

                <div class="card" style="padding: 0;">
                    <div style="padding: 20px 24px; border-bottom: 1px solid var(--gray-200);">
                        <h2><i class="fas fa-users"></i> All Users & Balances</h2>
                    </div>
                    <div class="table-container" style="margin: 0;">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>User</th>
                                    <th>Account Number</th>
                                    <th>Current Balance</th>
                                    <th>Status</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($users as $user): ?>
                                    <tr>
                                        <td><strong><?= htmlspecialchars($user['full_name']) ?></strong><br><small><?= htmlspecialchars($user['email']) ?></small>
                                        </td>
                                        <td><code><?= $user['account_number'] ?></code></td>
                                        <td><strong>$<?= number_format($user['balance'], 2) ?></strong></td>
                                        <td><span class="badge badge-active">Active</span></td>
                                        <td><a href="user-transactions.php?user_id=<?= $user['user_id'] ?>"
                                                class="btn-sm">View Transactions</a></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </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'));
        }
        document.addEventListener('click', (event) => {
            if (window.innerWidth <= 1024) {
                if (!sidebar.contains(event.target) && !hamburger.contains(event.target) && sidebar.classList.contains('mobile-open')) {
                    sidebar.classList.remove('mobile-open');
                }
            }
        });
    </script>
</body>

</html>