<?php
require_once('../database/header.php');

// Check if user is admin
if($userdata['usertype'] != 'mainadmin') {
    header('Location: index.php');
    exit;
}

require_once('../database/UpiPoolManager.php');
$upiManager = new UpiPoolManager($conn);

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_upi':
                try {
                    $stmt = $conn->prepare("INSERT INTO upi_pool (upi_id, upi_name, status, daily_limit) VALUES (?, ?, ?, ?)");
                    $stmt->execute([
                        $_POST['upi_id'],
                        $_POST['upi_name'],
                        $_POST['status'],
                        $_POST['daily_limit']
                    ]);
                    $success_msg = "UPI added successfully!";
                } catch (PDOException $e) {
                    if ($e->getCode() == 23000) {
                        $error_msg = "Error: This UPI ID already exists in the pool!";
                    } else {
                        $error_msg = "Error: " . $e->getMessage();
                    }
                }
                break;
                
            case 'update_upi':
                $stmt = $conn->prepare("UPDATE upi_pool SET upi_name = ?, status = ?, daily_limit = ? WHERE id = ?");
                $stmt->execute([
                    $_POST['upi_name'],
                    $_POST['status'],
                    $_POST['daily_limit'],
                    $_POST['upi_id']
                ]);
                $success_msg = "UPI updated successfully!";
                break;
                
            case 'delete_upi':
                $stmt = $conn->prepare("DELETE FROM upi_pool WHERE id = ?");
                $stmt->execute([$_POST['upi_id']]);
                $success_msg = "UPI deleted successfully!";
                break;
                
            case 'update_settings':
                try {
                    $alter = $conn->query("SHOW COLUMNS FROM settings LIKE 'bank_upi_payout_commission'");
                    if ($alter->rowCount() == 0) {
                        $conn->exec("ALTER TABLE settings ADD COLUMN bank_upi_payout_commission DECIMAL(10,2) DEFAULT 0.00 AFTER bank_upi_fixed");
                        $conn->exec("ALTER TABLE settings ADD COLUMN bank_upi_payout_fixed DECIMAL(10,2) DEFAULT 0.00 AFTER bank_upi_payout_commission");
                    }
                } catch(Exception $e) {}
                
                $stmt = $conn->prepare("
                    UPDATE settings SET 
                    default_gateway = ?,
                    bank_upi_commission = ?,
                    bank_upi_fixed = ?,
                    bank_upi_payout_commission = ?,
                    bank_upi_payout_fixed = ?,
                    upi_rotation_enabled = ?,
                    upi_rotation_interval = ?
                    WHERE id = 1
                ");
                $stmt->execute([
                    $_POST['default_gateway'],
                    $_POST['bank_upi_commission'],
                    $_POST['bank_upi_fixed'],
                    $_POST['bank_upi_payout_commission'],
                    $_POST['bank_upi_payout_fixed'],
                    isset($_POST['upi_rotation_enabled']) ? 1 : 0,
                    $_POST['upi_rotation_interval']
                ]);
                $success_msg = "Settings updated successfully!";
                break;
        }
    }
}

// Get all UPIs
$upis = $upiManager->getAllActiveUPIs();
$stmt = $conn->prepare("SELECT * FROM upi_pool ORDER BY id DESC");
$stmt->execute();
$all_upis = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get settings
$settings = $upiManager->getGatewaySettings();

// Stats
$total_upis = count($all_upis);
$active_upis = 0;
$total_daily_volume = 0;
$total_daily_limit = 0;
foreach ($all_upis as $u) {
    if ($u['status'] == 'active') $active_upis++;
    $total_daily_volume += $u['current_usage'];
    $total_daily_limit += $u['daily_limit'];
}
$limit_percent = $total_daily_limit > 0 ? round(($total_daily_volume / $total_daily_limit) * 100, 1) : 0;
?>

<style>
/* ============================================
   UPI POOL MANAGEMENT — PREMIUM LIGHT UI
   ============================================ */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap');

.upm-wrap,
.upm-wrap * {
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

.upm-wrap {
    background: #f4f6fa;
}

/* ---------- Page Header ---------- */
.upm-page-header {
    margin-bottom: 28px;
}

.upm-page-header h2 {
    font-size: 24px;
    font-weight: 800;
    color: #1e293b;
    margin: 0 0 4px;
}

.upm-page-header p {
    color: #94a3b8;
    font-size: 14px;
    margin: 0;
}

/* ---------- Alerts ---------- */
.upm-alert {
    padding: 14px 18px;
    border-radius: 12px;
    font-size: 13px;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 20px;
    animation: upmSlideIn 0.35s ease;
}

@keyframes upmSlideIn {
    from { opacity: 0; transform: translateY(-8px); }
    to { opacity: 1; transform: translateY(0); }
}

.upm-alert.success {
    background: #ecfdf5;
    border: 1px solid #a7f3d0;
    color: #065f46;
}

.upm-alert.error {
    background: #fef2f2;
    border: 1px solid #fecaca;
    color: #991b1b;
}

.upm-alert .dismiss-btn {
    margin-left: auto;
    background: none;
    border: none;
    font-size: 18px;
    color: inherit;
    cursor: pointer;
    opacity: 0.5;
    line-height: 1;
}

.upm-alert .dismiss-btn:hover { opacity: 1; }

/* ---------- Stats Row ---------- */
.upm-stats-row {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    margin-bottom: 28px;
}

.upm-stat-card {
    background: #fff;
    border-radius: 14px;
    padding: 20px;
    border: 1px solid #e8ecf1;
    box-shadow: 0 1px 3px rgba(0,0,0,0.04);
    transition: all 0.25s ease;
    position: relative;
    overflow: hidden;
}

.upm-stat-card:hover {
    box-shadow: 0 6px 20px rgba(0,0,0,0.06);
    transform: translateY(-2px);
}

.upm-stat-card::before {
    content: '';
    position: absolute;
    top: 0; left: 0; right: 0;
    height: 3px;
}

.upm-stat-card.st-total::before { background: #6366f1; }
.upm-stat-card.st-active::before { background: #10b981; }
.upm-stat-card.st-volume::before { background: #f59e0b; }
.upm-stat-card.st-limit::before { background: #3b82f6; }

.upm-stat-card .st-icon {
    width: 42px;
    height: 42px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    margin-bottom: 12px;
}

.st-total .st-icon { background: #eef2ff; color: #6366f1; }
.st-active .st-icon { background: #ecfdf5; color: #10b981; }
.st-volume .st-icon { background: #fffbeb; color: #f59e0b; }
.st-limit .st-icon { background: #eff6ff; color: #3b82f6; }

.upm-stat-card .st-label {
    font-size: 11px;
    font-weight: 600;
    color: #94a3b8;
    text-transform: uppercase;
    letter-spacing: 0.8px;
    margin-bottom: 4px;
}

.upm-stat-card .st-value {
    font-size: 22px;
    font-weight: 700;
    color: #1e293b;
}

/* ---------- Glass Card ---------- */
.upm-card {
    background: #fff;
    border-radius: 16px;
    border: 1px solid #e8ecf1;
    box-shadow: 0 1px 3px rgba(0,0,0,0.04);
    overflow: hidden;
    margin-bottom: 24px;
    transition: box-shadow 0.3s;
}

.upm-card:hover {
    box-shadow: 0 4px 16px rgba(0,0,0,0.06);
}

.upm-card-header {
    padding: 18px 24px;
    border-bottom: 1px solid #f1f5f9;
    display: flex;
    align-items: center;
    gap: 12px;
}

.upm-card-header .ch-icon {
    width: 36px;
    height: 36px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 17px;
}

.ch-icon.ch-settings { background: #eef2ff; color: #6366f1; }
.ch-icon.ch-add { background: #ecfdf5; color: #10b981; }
.ch-icon.ch-list { background: #fffbeb; color: #f59e0b; }

.upm-card-header h4 {
    font-size: 15px;
    font-weight: 700;
    color: #1e293b;
    margin: 0;
}

.upm-card-header .count-badge {
    margin-left: auto;
    background: #f1f5f9;
    color: #64748b;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.upm-card-body {
    padding: 24px;
}

/* ---------- Form Elements ---------- */
.upm-wrap .fm-label {
    display: block;
    font-size: 12px;
    font-weight: 600;
    color: #64748b;
    margin-bottom: 6px;
    text-transform: uppercase;
    letter-spacing: 0.3px;
}

.upm-wrap .fm-input,
.upm-wrap .fm-select {
    width: 100%;
    padding: 10px 14px;
    border: 1px solid #e2e8f0;
    border-radius: 10px;
    font-size: 14px;
    color: #1e293b;
    background: #fff;
    transition: all 0.25s ease;
    outline: none;
    font-family: 'Inter', sans-serif;
}

.upm-wrap .fm-input::placeholder {
    color: #cbd5e1;
}

.upm-wrap .fm-input:focus,
.upm-wrap .fm-select:focus {
    border-color: #6366f1;
    box-shadow: 0 0 0 3px rgba(99,102,241,0.08);
}

.upm-wrap .fm-hint {
    font-size: 11px;
    color: #94a3b8;
    margin-top: 4px;
}

/* ---------- Form Layout ---------- */
.fm-grid {
    display: grid;
    gap: 16px;
}

.fm-grid-2 { grid-template-columns: 1fr 1fr; }
.fm-grid-5 { grid-template-columns: 3fr 2fr 1.5fr 1.5fr auto; }

.fm-group { display: flex; flex-direction: column; }

/* ---------- Settings Sections ---------- */
.settings-section-label {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 14px;
}

.settings-section-label .dot-indicator {
    width: 8px;
    height: 8px;
    border-radius: 50%;
}

.settings-section-label .dot-indicator.green { background: #10b981; }
.settings-section-label .dot-indicator.red { background: #ef4444; }
.settings-section-label .dot-indicator.blue { background: #6366f1; }

.settings-section-label h5 {
    font-size: 14px;
    font-weight: 700;
    margin: 0;
}

.settings-section-label h5.text-green { color: #10b981; }
.settings-section-label h5.text-red { color: #ef4444; }
.settings-section-label h5.text-blue { color: #6366f1; }

/* Two column settings */
.settings-cols {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
}

.settings-col-box {
    padding: 20px;
    border-radius: 12px;
    background: #f8fafc;
    border: 1px solid #f1f5f9;
}

/* Divider */
.upm-divider {
    border: none;
    height: 1px;
    background: #f1f5f9;
    margin: 24px 0;
}

/* ---------- Toggle Switch ---------- */
.toggle-wrap {
    display: flex;
    align-items: center;
    gap: 12px;
}

.toggle-sw {
    position: relative;
    width: 44px;
    height: 24px;
    flex-shrink: 0;
}

.toggle-sw input { opacity: 0; width: 0; height: 0; }

.toggle-track {
    position: absolute;
    inset: 0;
    background: #e2e8f0;
    border-radius: 24px;
    cursor: pointer;
    transition: background 0.3s;
}

.toggle-track::after {
    content: '';
    position: absolute;
    top: 2px;
    left: 2px;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: #fff;
    box-shadow: 0 1px 3px rgba(0,0,0,0.15);
    transition: transform 0.3s;
}

.toggle-sw input:checked + .toggle-track {
    background: #6366f1;
}

.toggle-sw input:checked + .toggle-track::after {
    transform: translateX(20px);
}

.toggle-text {
    font-size: 14px;
    font-weight: 600;
    color: #334155;
}

/* ---------- Buttons ---------- */
.btn-upm {
    padding: 10px 22px;
    border-radius: 10px;
    border: none;
    font-size: 13px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.25s ease;
    font-family: 'Inter', sans-serif;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

.btn-upm-primary {
    background: #6366f1;
    color: #fff;
    box-shadow: 0 2px 8px rgba(99,102,241,0.25);
}

.btn-upm-primary:hover {
    background: #4f46e5;
    box-shadow: 0 4px 14px rgba(99,102,241,0.3);
    transform: translateY(-1px);
}

.btn-upm-success {
    background: #10b981;
    color: #fff;
    box-shadow: 0 2px 8px rgba(16,185,129,0.25);
}

.btn-upm-success:hover {
    background: #059669;
    box-shadow: 0 4px 14px rgba(16,185,129,0.3);
    transform: translateY(-1px);
}

/* Small action buttons */
.btn-act {
    padding: 6px 14px;
    border-radius: 8px;
    font-size: 12px;
    font-weight: 600;
    border: none;
    cursor: pointer;
    transition: all 0.2s ease;
    font-family: 'Inter', sans-serif;
    display: inline-flex;
    align-items: center;
    gap: 4px;
}

.btn-act-edit {
    background: #eef2ff;
    color: #6366f1;
}

.btn-act-edit:hover {
    background: #e0e7ff;
    transform: translateY(-1px);
}

.btn-act-delete {
    background: #fef2f2;
    color: #ef4444;
}

.btn-act-delete:hover {
    background: #fee2e2;
    transform: translateY(-1px);
}

/* ---------- Table ---------- */
.upm-table {
    width: 100%;
    border-collapse: collapse;
}

.upm-table thead th {
    padding: 12px 16px;
    font-size: 11px;
    font-weight: 600;
    color: #94a3b8;
    text-transform: uppercase;
    letter-spacing: 0.8px;
    border-bottom: 1px solid #f1f5f9;
    text-align: left;
    white-space: nowrap;
    background: #fafbfc;
}

.upm-table tbody tr {
    border-bottom: 1px solid #f8fafc;
    transition: background 0.15s;
}

.upm-table tbody tr:last-child { border-bottom: none; }

.upm-table tbody tr:hover {
    background: #f8fafc;
}

.upm-table tbody td {
    padding: 14px 16px;
    font-size: 13px;
    color: #475569;
    vertical-align: middle;
    white-space: nowrap;
}

.upm-table .upi-id-code {
    display: inline-block;
    font-family: 'SFMono-Regular', 'Consolas', monospace;
    background: #f1f5f9;
    color: #6366f1;
    padding: 3px 10px;
    border-radius: 6px;
    font-size: 12px;
    font-weight: 500;
}

/* Status pill */
.status-pill {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
    letter-spacing: 0.3px;
}

.status-pill.is-active {
    background: #ecfdf5;
    color: #059669;
}

.status-pill.is-inactive {
    background: #f1f5f9;
    color: #94a3b8;
}

.status-pill .pill-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
}

.status-pill.is-active .pill-dot { background: #10b981; }
.status-pill.is-inactive .pill-dot { background: #cbd5e1; }

/* Usage bar in table */
.usage-cell-wrap {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.usage-mini-bar {
    width: 70px;
    height: 4px;
    background: #f1f5f9;
    border-radius: 2px;
    overflow: hidden;
}

.usage-mini-fill {
    height: 100%;
    border-radius: 2px;
    background: #6366f1;
    transition: width 0.5s ease;
}

/* Rate bar in table */
.rate-cell-wrap {
    display: flex;
    align-items: center;
    gap: 8px;
}

.rate-mini-bar {
    width: 50px;
    height: 5px;
    background: #f1f5f9;
    border-radius: 3px;
    overflow: hidden;
}

.rate-mini-fill {
    height: 100%;
    border-radius: 3px;
    transition: width 0.5s ease;
}

.rate-mini-fill.r-high { background: #10b981; }
.rate-mini-fill.r-mid { background: #f59e0b; }
.rate-mini-fill.r-low { background: #ef4444; }

.rate-pct {
    font-size: 12px;
    font-weight: 600;
}

.rate-pct.r-high { color: #10b981; }
.rate-pct.r-mid { color: #f59e0b; }
.rate-pct.r-low { color: #ef4444; }

/* Action cell */
.act-cell {
    display: flex;
    gap: 6px;
}

/* Empty State */
.empty-state {
    text-align: center;
    padding: 50px 20px;
    color: #cbd5e1;
}

.empty-state i {
    font-size: 48px;
    display: block;
    margin-bottom: 12px;
}

.empty-state p {
    font-size: 14px;
    margin: 0;
}

/* ---------- Modal ---------- */
.upm-modal .modal-content {
    border-radius: 16px;
    border: 1px solid #e8ecf1;
    overflow: hidden;
    box-shadow: 0 20px 60px rgba(0,0,0,0.12);
}

.upm-modal .modal-header {
    padding: 18px 24px;
    border-bottom: 1px solid #f1f5f9;
    background: #fafbfc;
}

.upm-modal .modal-title {
    font-size: 16px;
    font-weight: 700;
    color: #1e293b;
    display: flex;
    align-items: center;
    gap: 8px;
}

.upm-modal .modal-body {
    padding: 24px;
}

.upm-modal .modal-footer {
    padding: 16px 24px;
    border-top: 1px solid #f1f5f9;
    background: #fafbfc;
}

.btn-modal-cancel {
    padding: 8px 18px;
    border-radius: 8px;
    border: 1px solid #e2e8f0;
    background: #fff;
    color: #64748b;
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    font-family: 'Inter', sans-serif;
}

.btn-modal-cancel:hover {
    background: #f8fafc;
    border-color: #cbd5e1;
}

/* ---------- Responsive ---------- */
@media (max-width: 1200px) {
    .upm-stats-row { grid-template-columns: repeat(2, 1fr); }
    .fm-grid-5 { grid-template-columns: 1fr 1fr; }
}

@media (max-width: 768px) {
    .upm-stats-row { grid-template-columns: 1fr; }
    .settings-cols { grid-template-columns: 1fr; }
    .fm-grid-5 { grid-template-columns: 1fr; }
    .fm-grid-2 { grid-template-columns: 1fr; }
    .upm-wrap { padding: 16px; }
}
</style>

<div class="main-panel">
    <div class="content-wrapper upm-wrap">

        <!-- Page Header -->
        <div class="upm-page-header">
            <h2>UPI Pool Management</h2>
            <p>Manage multiple UPI IDs with auto-rotation</p>
        </div>

        <!-- Alerts -->
        <?php if (isset($success_msg)): ?>
            <div class="upm-alert success">
                <i class="mdi mdi-check-circle"></i>
                <?= $success_msg ?>
                <button class="dismiss-btn" onclick="this.parentElement.remove();">&times;</button>
            </div>
        <?php endif; ?>

        <?php if (isset($error_msg)): ?>
            <div class="upm-alert error">
                <i class="mdi mdi-alert-circle"></i>
                <?= $error_msg ?>
                <button class="dismiss-btn" onclick="this.parentElement.remove();">&times;</button>
            </div>
        <?php endif; ?>

        <!-- Stats Row -->
        <div class="upm-stats-row">
            <div class="upm-stat-card st-total">
                <div class="st-icon"><i class="mdi mdi-cube-outline"></i></div>
                <div class="st-label">Total UPIs</div>
                <div class="st-value"><?= $total_upis ?></div>
            </div>
            <div class="upm-stat-card st-active">
                <div class="st-icon"><i class="mdi mdi-check-network-outline"></i></div>
                <div class="st-label">Active UPIs</div>
                <div class="st-value"><?= $active_upis ?></div>
            </div>
            <div class="upm-stat-card st-volume">
                <div class="st-icon"><i class="mdi mdi-chart-line"></i></div>
                <div class="st-label">Today's Volume</div>
                <div class="st-value">₹<?= number_format($total_daily_volume, 0) ?></div>
            </div>
            <div class="upm-stat-card st-limit">
                <div class="st-icon"><i class="mdi mdi-gauge"></i></div>
                <div class="st-label">Limit Used</div>
                <div class="st-value"><?= $limit_percent ?>%</div>
            </div>
        </div>

        <!-- Gateway Settings -->
        <div class="upm-card">
            <div class="upm-card-header">
                <div class="ch-icon ch-settings"><i class="mdi mdi-cog"></i></div>
                <h4>Gateway Settings</h4>
            </div>
            <div class="upm-card-body">
                <form method="POST">
                    <input type="hidden" name="action" value="update_settings">

                    <!-- Gateway Config -->
                    <div class="settings-section-label">
                        <div class="dot-indicator blue"></div>
                        <h5 class="text-blue">Gateway Configuration</h5>
                    </div>
                    <div class="fm-grid fm-grid-2" style="max-width:600px; margin-bottom:24px;">
                        <div class="fm-group">
                            <label class="fm-label">Default Gateway Mode</label>
                            <select name="default_gateway" class="fm-select">
                                <option value="rspay" <?= $settings['default_gateway'] == 'rspay' ? 'selected' : '' ?>>RSPay (Aggregator)</option>
                                <option value="bank_upi" <?= $settings['default_gateway'] == 'bank_upi' ? 'selected' : '' ?>>Bank UPI (Own Gateway)</option>
                                <option value="auto" <?= $settings['default_gateway'] == 'auto' ? 'selected' : '' ?>>Auto (Smart Selection)</option>
                            </select>
                        </div>
                    </div>

                    <!-- Pay In / Pay Out -->
                    <div class="settings-cols">
                        <div class="settings-col-box">
                            <div class="settings-section-label">
                                <div class="dot-indicator green"></div>
                                <h5 class="text-green">Pay In Settings (Deposit)</h5>
                            </div>
                            <div class="fm-grid fm-grid-2">
                                <div class="fm-group">
                                    <label class="fm-label">Commission (%)</label>
                                    <input type="number" step="0.01" name="bank_upi_commission" class="fm-input" value="<?= $settings['bank_upi_commission'] ?>">
                                </div>
                                <div class="fm-group">
                                    <label class="fm-label">Fixed Fee (₹)</label>
                                    <input type="number" step="0.01" name="bank_upi_fixed" class="fm-input" value="<?= $settings['bank_upi_fixed'] ?>">
                                </div>
                            </div>
                        </div>
                        <div class="settings-col-box">
                            <div class="settings-section-label">
                                <div class="dot-indicator red"></div>
                                <h5 class="text-red">Pay Out Settings (Withdrawal)</h5>
                            </div>
                            <div class="fm-grid fm-grid-2">
                                <div class="fm-group">
                                    <label class="fm-label">Commission (%)</label>
                                    <input type="number" step="0.01" name="bank_upi_payout_commission" class="fm-input" value="<?= $settings['bank_upi_payout_commission'] ?? 0 ?>">
                                </div>
                                <div class="fm-group">
                                    <label class="fm-label">Fixed Fee (₹)</label>
                                    <input type="number" step="0.01" name="bank_upi_payout_fixed" class="fm-input" value="<?= $settings['bank_upi_payout_fixed'] ?? 0 ?>">
                                </div>
                            </div>
                        </div>
                    </div>

                    <hr class="upm-divider">

                    <!-- Rotation -->
                    <div class="fm-grid fm-grid-2">
                        <div class="fm-group" style="justify-content:center;">
                            <div class="toggle-wrap">
                                <label class="toggle-sw">
                                    <input type="checkbox" name="upi_rotation_enabled" <?= $settings['upi_rotation_enabled'] ? 'checked' : '' ?>>
                                    <span class="toggle-track"></span>
                                </label>
                                <span class="toggle-text">Enable UPI Auto-Rotation Logic</span>
                            </div>
                        </div>
                        <div class="fm-group">
                            <label class="fm-label">Rotation Interval (seconds)</label>
                            <input type="number" name="upi_rotation_interval" class="fm-input" value="<?= $settings['upi_rotation_interval'] ?>">
                            <span class="fm-hint">Time before switching to next UPI ID</span>
                        </div>
                    </div>

                    <div style="margin-top:24px;">
                        <button type="submit" class="btn-upm btn-upm-primary">
                            <i class="mdi mdi-content-save"></i> Save Settings
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Add New UPI -->
        <div class="upm-card">
            <div class="upm-card-header">
                <div class="ch-icon ch-add"><i class="mdi mdi-plus-circle-outline"></i></div>
                <h4>Add New UPI</h4>
            </div>
            <div class="upm-card-body">
                <form method="POST">
                    <input type="hidden" name="action" value="add_upi">
                    <div class="fm-grid fm-grid-5">
                        <div class="fm-group">
                            <label class="fm-label">UPI ID</label>
                            <input type="text" name="upi_id" class="fm-input" placeholder="merchant@paytm" required>
                        </div>
                        <div class="fm-group">
                            <label class="fm-label">UPI Name</label>
                            <input type="text" name="upi_name" class="fm-input" placeholder="Paytm UPI 1" required>
                        </div>
                        <div class="fm-group">
                            <label class="fm-label">Status</label>
                            <select name="status" class="fm-select">
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                        </div>
                        <div class="fm-group">
                            <label class="fm-label">Daily Limit (₹)</label>
                            <input type="number" step="0.01" name="daily_limit" class="fm-input" value="100000" required>
                        </div>
                        <div class="fm-group" style="justify-content:flex-end;">
                            <button type="submit" class="btn-upm btn-upm-success" style="height:42px;">
                                <i class="mdi mdi-plus"></i> Add
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- UPI Pool List -->
        <div class="upm-card">
            <div class="upm-card-header">
                <div class="ch-icon ch-list"><i class="mdi mdi-format-list-bulleted"></i></div>
                <h4>UPI Pool</h4>
                <span class="count-badge"><?= count($all_upis) ?> Total</span>
            </div>
            <div style="overflow-x:auto;">
                <table class="upm-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>UPI ID</th>
                            <th>Name</th>
                            <th>Status</th>
                            <th>Daily Limit</th>
                            <th>Current Usage</th>
                            <th>Last Used</th>
                            <th>Transactions</th>
                            <th>Success Rate</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($all_upis as $upi): ?>
                            <?php 
                                $stats = $upiManager->getUPIStats($upi['upi_id']);
                                $usage_pct = $upi['daily_limit'] > 0 ? min(100, round(($upi['current_usage'] / $upi['daily_limit']) * 100)) : 0;
                                $rate_class = $upi['success_rate'] >= 80 ? 'r-high' : ($upi['success_rate'] >= 50 ? 'r-mid' : 'r-low');
                                $rate_text_class = $rate_class;
                            ?>
                            <tr>
                                <td style="color:#94a3b8; font-size:12px;">#<?= $upi['id'] ?></td>
                                <td><span class="upi-id-code"><?= htmlspecialchars($upi['upi_id']) ?></span></td>
                                <td style="font-weight:500; color:#1e293b;"><?= htmlspecialchars($upi['upi_name']) ?></td>
                                <td>
                                    <span class="status-pill <?= $upi['status'] == 'active' ? 'is-active' : 'is-inactive' ?>">
                                        <span class="pill-dot"></span>
                                        <?= ucfirst($upi['status']) ?>
                                    </span>
                                </td>
                                <td style="font-weight:600; color:#1e293b;">₹<?= number_format($upi['daily_limit'], 0) ?></td>
                                <td>
                                    <div class="usage-cell-wrap">
                                        <span style="font-size:12px; color:#475569;">₹<?= number_format($upi['current_usage'], 0) ?></span>
                                        <div class="usage-mini-bar">
                                            <div class="usage-mini-fill" style="width:<?= $usage_pct ?>%;"></div>
                                        </div>
                                    </div>
                                </td>
                                <td style="font-size:12px; color:#94a3b8;">
                                    <?= $upi['last_used'] ? date('d M, h:i A', strtotime($upi['last_used'])) : 'Never' ?>
                                </td>
                                <td style="font-weight:600; color:#1e293b;"><?= $upi['total_transactions'] ?></td>
                                <td>
                                    <div class="rate-cell-wrap">
                                        <div class="rate-mini-bar">
                                            <div class="rate-mini-fill <?= $rate_class ?>" style="width:<?= $upi['success_rate'] ?>%;"></div>
                                        </div>
                                        <span class="rate-pct <?= $rate_text_class ?>"><?= number_format($upi['success_rate'], 1) ?>%</span>
                                    </div>
                                </td>
                                <td>
                                    <div class="act-cell">
                                        <button class="btn-act btn-act-edit" onclick="editUPI(<?= htmlspecialchars(json_encode($upi)) ?>)">
                                            <i class="mdi mdi-pencil"></i> Edit
                                        </button>
                                        <form method="POST" style="display:inline;" onsubmit="return confirm('Delete this UPI?')">
                                            <input type="hidden" name="action" value="delete_upi">
                                            <input type="hidden" name="upi_id" value="<?= $upi['id'] ?>">
                                            <button type="submit" class="btn-act btn-act-delete">
                                                <i class="mdi mdi-delete"></i> Delete
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>

                        <?php if (empty($all_upis)): ?>
                            <tr>
                                <td colspan="10">
                                    <div class="empty-state">
                                        <i class="mdi mdi-inbox-multiple"></i>
                                        <p>No UPI IDs added yet. Add your first UPI above.</p>
                                    </div>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </div>
<!-- content-wrapper ends -->

<!-- Edit Modal -->
<div class="modal fade upm-modal" id="editModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="mdi mdi-pencil" style="color:#6366f1;"></i> Edit UPI</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="update_upi">
                    <input type="hidden" name="upi_id" id="edit_id">
                    
                    <div class="fm-group" style="margin-bottom:16px;">
                        <label class="fm-label">UPI ID</label>
                        <input type="text" id="edit_upi_id" class="fm-input" readonly style="background:#f8fafc; color:#94a3b8;">
                    </div>
                    
                    <div class="fm-group" style="margin-bottom:16px;">
                        <label class="fm-label">UPI Name</label>
                        <input type="text" name="upi_name" id="edit_upi_name" class="fm-input" required>
                    </div>
                    
                    <div class="fm-grid fm-grid-2">
                        <div class="fm-group">
                            <label class="fm-label">Status</label>
                            <select name="status" id="edit_status" class="fm-select">
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                        </div>
                        <div class="fm-group">
                            <label class="fm-label">Daily Limit (₹)</label>
                            <input type="number" step="0.01" name="daily_limit" id="edit_daily_limit" class="fm-input" required>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-modal-cancel" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn-upm btn-upm-primary">
                        <i class="mdi mdi-check"></i> Save Changes
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function editUPI(upi) {
    document.getElementById('edit_id').value = upi.id;
    document.getElementById('edit_upi_id').value = upi.upi_id;
    document.getElementById('edit_upi_name').value = upi.upi_name;
    document.getElementById('edit_status').value = upi.status;
    document.getElementById('edit_daily_limit').value = upi.daily_limit;
    $('#editModal').modal('show');
}

// Auto dismiss alerts
document.querySelectorAll('.upm-alert').forEach(function(el) {
    setTimeout(function() {
        el.style.opacity = '0';
        el.style.transform = 'translateY(-8px)';
        el.style.transition = 'all 0.3s ease';
        setTimeout(function() { el.remove(); }, 300);
    }, 5000);
});
</script>

<?php require_once('../database/footer.php'); ?>
