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

redirectIfNotAdmin();

$error = '';
$success = '';

// Handle card actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $card_id = intval($_POST['card_id'] ?? 0);

    try {
        if ($action === 'issue_card') {
            $user_id = intval($_POST['user_id']);
            $card_type = $_POST['card_type'];
            $daily_limit = floatval($_POST['daily_limit']);
            $monthly_limit = floatval($_POST['monthly_limit']);
            $per_transaction_limit = floatval($_POST['per_transaction_limit']);

            // Get user account
            $stmt = $pdo->prepare("SELECT account_id, account_number FROM accounts WHERE user_id = ?");
            $stmt->execute([$user_id]);
            $account = $stmt->fetch();

            if (!$account) {
                throw new Exception("User account not found.");
            }

            // Generate card details
            $card_number = generateCardNumber();
            $expiry_date = date('Y-m-d', strtotime('+3 years'));
            $cvv = rand(100, 999);

            $stmt = $pdo->prepare("
                INSERT INTO virtual_cards (user_id, account_id, card_number, card_holder_name, expiry_date, cvv, card_type, daily_limit, monthly_limit, per_transaction_limit)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");

            $card_holder_name = strtoupper($_POST['card_holder_name']);
            $stmt->execute([$user_id, $account['account_id'], $card_number, $card_holder_name, $expiry_date, $cvv, $card_type, $daily_limit, $monthly_limit, $per_transaction_limit]);

            $success = "Virtual card issued successfully. Card number: " . maskCardNumber($card_number);

        } elseif ($action === 'block_card') {
            $stmt = $pdo->prepare("UPDATE virtual_cards SET card_status = 'blocked', blocked_at = NOW() WHERE card_id = ?");
            $stmt->execute([$card_id]);
            $success = "Card blocked successfully.";

        } elseif ($action === 'unblock_card') {
            $stmt = $pdo->prepare("UPDATE virtual_cards SET card_status = 'active', blocked_at = NULL WHERE card_id = ?");
            $stmt->execute([$card_id]);
            $success = "Card unblocked successfully.";

        } elseif ($action === 'update_limits') {
            $daily_limit = floatval($_POST['daily_limit']);
            $monthly_limit = floatval($_POST['monthly_limit']);
            $per_transaction_limit = floatval($_POST['per_transaction_limit']);

            $stmt = $pdo->prepare("UPDATE virtual_cards SET daily_limit = ?, monthly_limit = ?, per_transaction_limit = ? WHERE card_id = ?");
            $stmt->execute([$daily_limit, $monthly_limit, $per_transaction_limit, $card_id]);
            $success = "Card limits updated successfully.";
        }

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

// Fetch all users for dropdown
$users = $pdo->query("SELECT user_id, full_name FROM users WHERE status = 'approved' ORDER BY full_name")->fetchAll();

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

function generateCardNumber()
{
    $prefix = '4'; // Visa prefix
    $number = $prefix;
    for ($i = 0; $i < 15; $i++) {
        $number .= rand(0, 9);
    }
    return $number;
}

function maskCardNumber($number)
{
    return '**** **** **** ' . substr($number, -4);
}

function getCardStatusBadge($status)
{
    $badges = [
        'active' => '<span class="badge badge-success">Active</span>',
        'blocked' => '<span class="badge badge-danger">Blocked</span>',
        'expired' => '<span class="badge badge-warning">Expired</span>',
        'cancelled' => '<span class="badge badge-secondary">Cancelled</span>'
    ];
    return $badges[$status] ?? '<span class="badge">' . $status . '</span>';
}

$adminInfo = $pdo->prepare("SELECT full_name FROM users WHERE user_id = ?");
$adminInfo->execute([$_SESSION['user_id']]);
$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>Card Management - 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;
            --warning-orange: #f39c12;
            --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);
        }

        .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 {
            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 {
            border-color: var(--primary-blue);
            box-shadow: 0 0 0 3px rgba(26, 77, 140, 0.1);
        }

        .form-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
        }

        .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);
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 12px;
            border-radius: 8px;
            border: none;
            cursor: pointer;
            transition: var(--transition);
        }

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

        .btn-success:hover {
            background: var(--success-green);
            color: white;
        }

        .btn-danger {
            background: rgba(220, 53, 69, 0.1);
            color: var(--error-red);
        }

        .btn-danger:hover {
            background: var(--error-red);
            color: white;
        }

        .btn-warning {
            background: rgba(243, 156, 18, 0.1);
            color: var(--warning-orange);
        }

        .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: 800px;
        }

        .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-success {
            background: rgba(46, 125, 50, 0.1);
            color: var(--success-green);
        }

        .badge-danger {
            background: rgba(220, 53, 69, 0.1);
            color: var(--error-red);
        }

        .badge-warning {
            background: rgba(243, 156, 18, 0.1);
            color: var(--warning-orange);
        }

        .card-number {
            font-family: monospace;
            font-size: 16px;
            letter-spacing: 2px;
        }

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

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

            .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;
            }

            .form-row {
                grid-template-columns: 1fr;
            }
        }
    </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="card-management.php" class="nav-link active"><i
                            class="fas fa-credit-card"></i> Card Management</a></div>
                <div class="nav-item"><a href="manage-balance.php" class="nav-link"><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="recent_transactions.php" class="nav-link"><i
                            class="fas fa-exchange-alt"></i> Transactions</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>Card Management</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; ?>

                <!-- Issue New Card -->
                <div class="card">
                    <h2><i class="fas fa-plus-circle"></i> Issue New Virtual Card</h2>
                    <form method="POST">
                        <input type="hidden" name="action" value="issue_card">
                        <div class="form-row">
                            <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']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>Card Holder Name</label>
                                <input type="text" name="card_holder_name" placeholder="As per account" required>
                            </div>
                            <div class="form-group">
                                <label>Card Type</label>
                                <select name="card_type">
                                    <option value="virtual">Virtual Card</option>
                                    <option value="physical">Physical Card</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label>Daily Limit ($)</label>
                                <input type="number" name="daily_limit" step="0.01" value="50000" required>
                            </div>
                            <div class="form-group">
                                <label>Monthly Limit ($)</label>
                                <input type="number" name="monthly_limit" step="0.01" value="500000" required>
                            </div>
                            <div class="form-group">
                                <label>Per Transaction Limit ($)</label>
                                <input type="number" name="per_transaction_limit" step="0.01" value="25000" required>
                            </div>
                        </div>
                        <button type="submit" class="btn-primary"><i class="fas fa-credit-card"></i> Issue Card</button>
                    </form>
                </div>

                <!-- Cards List -->
                <div class="card" style="padding: 0;">
                    <div style="padding: 20px 24px; border-bottom: 1px solid var(--gray-200);">
                        <h2><i class="fas fa-credit-card"></i> All Cards</h2>
                    </div>
                    <div class="table-container" style="margin: 0;">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Card Number</th>
                                    <th>Card Holder</th>
                                    <th>User</th>
                                    <th>Type</th>
                                    <th>Status</th>
                                    <th>Daily Limit</th>
                                    <th>Monthly Limit</th>
                                    <th>Actions</th>
                            </thead>
                            <tbody>
                                <?php foreach ($cards as $card): ?>
                                    <tr>
                                        <td><span class="card-number"><?= maskCardNumber($card['card_number']) ?></span><br>
                                            <small>Exp: <?= date('m/y', strtotime($card['expiry_date'])) ?></small>
                                        </td>
                                        <td><strong><?= htmlspecialchars($card['card_holder_name']) ?></strong></td>
                                        <td><?= htmlspecialchars($card['full_name']) ?><br><small><?= $card['account_number'] ?></small>
                                        </td>
                                        <td><?= ucfirst($card['card_type']) ?></td>
                                        <td><?= getCardStatusBadge($card['card_status']) ?></td>
                                        <td>$<?= number_format($card['daily_limit'], 2) ?><br>
                                            <small>Spent: $<?= number_format($card['current_daily_spent'], 2) ?></small>
                                        </td>
                                        <td>$<?= number_format($card['monthly_limit'], 2) ?><br>
                                            <small>Spent: $<?= number_format($card['current_monthly_spent'], 2) ?></small>
                                        </td>
                                        <td>
                                            <?php if ($card['card_status'] === 'active'): ?>
                                                <form method="POST" style="display: inline;">
                                                    <input type="hidden" name="action" value="block_card">
                                                    <input type="hidden" name="card_id" value="<?= $card['card_id'] ?>">
                                                    <button type="submit" class="btn-sm btn-danger"
                                                        onclick="return confirm('Block this card?')">
                                                        <i class="fas fa-ban"></i> Block
                                                    </button>
                                                </form>
                                            <?php elseif ($card['card_status'] === 'blocked'): ?>
                                                <form method="POST" style="display: inline;">
                                                    <input type="hidden" name="action" value="unblock_card">
                                                    <input type="hidden" name="card_id" value="<?= $card['card_id'] ?>">
                                                    <button type="submit" class="btn-sm btn-success"
                                                        onclick="return confirm('Unblock this card?')">
                                                        <i class="fas fa-check"></i> Unblock
                                                    </button>
                                                </form>
                                            <?php endif; ?>
                                            <button
                                                onclick="openLimitModal(<?= $card['card_id'] ?>, <?= $card['daily_limit'] ?>, <?= $card['monthly_limit'] ?>, <?= $card['per_transaction_limit'] ?>)"
                                                class="btn-sm" style="background: var(--gray-100); cursor: pointer;">
                                                <i class="fas fa-sliders-h"></i> Limits
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- Limit Update Modal -->
    <div id="limitModal"
        style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 1000; align-items: center; justify-content: center;">
        <div style="background: white; border-radius: 24px; max-width: 500px; width: 90%; padding: 24px;">
            <h3 style="margin-bottom: 20px;">Update Card Limits</h3>
            <form method="POST" id="limitForm">
                <input type="hidden" name="action" value="update_limits">
                <input type="hidden" name="card_id" id="limit_card_id">
                <div class="form-group">
                    <label>Daily Limit ($)</label>
                    <input type="number" name="daily_limit" id="limit_daily" step="0.01" required>
                </div>
                <div class="form-group">
                    <label>Monthly Limit ($)</label>
                    <input type="number" name="monthly_limit" id="limit_monthly" step="0.01" required>
                </div>
                <div class="form-group">
                    <label>Per Transaction Limit ($)</label>
                    <input type="number" name="per_transaction_limit" id="limit_per_transaction" step="0.01" required>
                </div>
                <div style="display: flex; gap: 12px; justify-content: flex-end;">
                    <button type="button" onclick="closeLimitModal()" class="btn-sm"
                        style="background: var(--gray-100);">Cancel</button>
                    <button type="submit" class="btn-primary" style="padding: 8px 20px;">Save Changes</button>
                </div>
            </form>
        </div>
    </div>

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

        function openLimitModal(cardId, daily, monthly, perTransaction) {
            document.getElementById('limit_card_id').value = cardId;
            document.getElementById('limit_daily').value = daily;
            document.getElementById('limit_monthly').value = monthly;
            document.getElementById('limit_per_transaction').value = perTransaction;
            document.getElementById('limitModal').style.display = 'flex';
        }

        function closeLimitModal() {
            document.getElementById('limitModal').style.display = 'none';
        }

        window.onclick = function (event) {
            if (event.target === document.getElementById('limitModal')) closeLimitModal();
        }
    </script>
</body>

</html>