<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/middleware.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/payments.php';
require_once __DIR__ . '/../includes/notifications.php';
require_admin();

$action = $_POST['action'] ?? '';

// Handle Actions
if ($action === 'approve') {
    ensure_csrf();
    $pid = (int)($_POST['payment_id'] ?? 0);
    $note = sanitize_str($_POST['admin_note'] ?? '');
    
    // Get payment details
    $pay = $pdo->prepare("SELECT * FROM payments WHERE id=?"); $pay->execute([$pid]); $p = $pay->fetch();
    
    if ($p && $p['status'] !== 'confirmed') {
        $pdo->prepare("UPDATE payments SET status='confirmed', admin_note=? WHERE id=?")->execute([$note, $pid]);
        // Update application status
        $pdo->prepare("UPDATE applications SET status='processing', updated_at=? WHERE id=?")->execute([date('c'), $p['application_id']]);
        
        // Notify user
        $u = $pdo->prepare("SELECT u.email, u.full_name, u.id FROM applications a JOIN users u ON a.user_id=u.id WHERE a.id=?");
        $u->execute([$p['application_id']]);
        $user = $u->fetch();
        if ($user) {
            notify_inapp($pdo, (int)$user['id'], 'payment_approved', 'Payment Approved', "Your payment of ₦".number_format((float)$p['amount'])." has been approved.");
            queue_email($pdo, $user['email'], 'Payment Approved', 'default', ['message' => "Your payment of ₦".number_format((float)$p['amount'])." for Application #{$p['application_id']} has been approved. We are now processing your application."]);
            
            // Award commission if not already awarded (just in case manual approval is the trigger)
            award_commission($pdo, (int)$user['id'], (int)$p['application_id'], (float)$p['amount']);
        }
        set_flash('success', 'Payment approved successfully.');
    }
    redirect('/admin/payments.php');
}

if ($action === 'reject') {
    ensure_csrf();
    $pid = (int)($_POST['payment_id'] ?? 0);
    $note = sanitize_str($_POST['admin_note'] ?? '');
    
    $pay = $pdo->prepare("SELECT * FROM payments WHERE id=?"); $pay->execute([$pid]); $p = $pay->fetch();
    
    if ($p && $p['status'] !== 'rejected') {
        $pdo->prepare("UPDATE payments SET status='rejected', admin_note=? WHERE id=?")->execute([$note, $pid]);
        
        // Notify user
        $u = $pdo->prepare("SELECT u.email, u.full_name, u.id FROM applications a JOIN users u ON a.user_id=u.id WHERE a.id=?");
        $u->execute([$p['application_id']]);
        $user = $u->fetch();
        if ($user) {
            notify_inapp($pdo, (int)$user['id'], 'payment_rejected', 'Payment Rejected', "Your payment of ₦".number_format((float)$p['amount'])." was rejected. Reason: $note");
            queue_email($pdo, $user['email'], 'Payment Rejected', 'default', ['message' => "Your payment of ₦".number_format((float)$p['amount'])." for Application #{$p['application_id']} has been rejected. Reason: $note. Please contact support or try again."]);
        }
        set_flash('success', 'Payment rejected.');
    }
    redirect('/admin/payments.php');
}

// Filters
$status = $_GET['status'] ?? '';
$search = $_GET['q'] ?? '';

// Build Query
$sql = "SELECT p.*, u.full_name, u.email, a.service_id, s.service_name 
        FROM payments p 
        JOIN applications a ON p.application_id = a.id 
        JOIN users u ON a.user_id = u.id 
        JOIN services s ON a.service_id = s.id 
        WHERE 1=1";
$params = [];

if ($status) {
    $sql .= " AND p.status = ?";
    $params[] = $status;
}
if ($search) {
    $sql .= " AND (p.payment_reference LIKE ? OR u.full_name LIKE ? OR u.email LIKE ?)";
    $term = "%$search%";
    $params[] = $term; $params[] = $term; $params[] = $term;
}

$sql .= " ORDER BY p.created_at DESC";

// Export
if (($_GET['export'] ?? '') === 'csv') {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll();
    
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="payments_export_'.date('Y-m-d').'.csv"');
    $f = fopen('php://output', 'w');
    fputcsv($f, ['ID', 'Date', 'Reference', 'Amount', 'Status', 'Method', 'User', 'Email', 'Service', 'Admin Note']);
    foreach ($rows as $r) {
        fputcsv($f, [
            $r['id'], $r['created_at'], $r['payment_reference'], $r['amount'], $r['status'], 
            $r['method'] ?? '', $r['full_name'], $r['email'], $r['service_name'], $r['admin_note'] ?? ''
        ]);
    }
    fclose($f);
    exit;
}

// Pagination
$page = (int)($_GET['page'] ?? 1);
$perPage = 20;
$offset = ($page - 1) * $perPage;

$countSql = str_replace("p.*, u.full_name, u.email, a.service_id, s.service_name", "COUNT(*)", $sql);
$stmt = $pdo->prepare($countSql);
$stmt->execute($params);
$total = (int)$stmt->fetchColumn();
$totalPages = ceil($total / $perPage);

$sql .= " LIMIT $perPage OFFSET $offset";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$payments = $stmt->fetchAll();

// Stats
$stats = [
    'pending' => $pdo->query("SELECT COUNT(*) FROM payments WHERE status='pending'")->fetchColumn(),
    'confirmed' => $pdo->query("SELECT COUNT(*) FROM payments WHERE status='confirmed'")->fetchColumn(),
    'rejected' => $pdo->query("SELECT COUNT(*) FROM payments WHERE status='rejected'")->fetchColumn(),
    'total_vol' => $pdo->query("SELECT SUM(amount) FROM payments WHERE status='confirmed'")->fetchColumn() ?: 0
];

include __DIR__ . '/../includes/header.php';
?>
<style>
/* Payments Admin Styles */
.admin-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 32px; gap: 16px; flex-wrap: wrap; }
.admin-title { margin: 0; font-size: 28px; font-weight: 800; color: var(--text); letter-spacing: -0.5px; }

/* KPI Stats */
.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 20px; margin-bottom: 32px; }
.stat-card { background: #fff; border: 1px solid var(--border); border-radius: 20px; padding: 24px; display: flex; align-items: flex-start; gap: 16px; }
.stat-icon { width: 48px; height: 48px; border-radius: 14px; display: flex; align-items: center; justify-content: center; font-size: 20px; }
.stat-info { flex: 1; }
.stat-value { font-size: 24px; font-weight: 800; color: var(--text); line-height: 1; margin-bottom: 6px; }
.stat-label { font-size: 13px; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px; }

.stat-pending { border-left: 4px solid #f59e0b; }
.stat-pending .stat-icon { background: #fef3c7; color: #d97706; }
.stat-confirmed { border-left: 4px solid #10b981; }
.stat-confirmed .stat-icon { background: #ecfdf5; color: #059669; }
.stat-rejected { border-left: 4px solid #ef4444; }
.stat-rejected .stat-icon { background: #fef2f2; color: #dc2626; }
.stat-volume { border-left: 4px solid #6366f1; }
.stat-volume .stat-icon { background: #eef2ff; color: #4f46e5; }

/* Filter Bar */
.filter-card { background: #fff; border: 1px solid var(--border); border-radius: 20px; padding: 20px; margin-bottom: 24px; }
.filter-form { display: flex; gap: 12px; flex-wrap: wrap; align-items: flex-end; }
.search-input-wrapper { flex: 1; min-width: 280px; position: relative; }
.search-input { width: 100%; padding: 12px 16px; padding-left: 44px; border: 1px solid var(--border); border-radius: 12px; font-size: 15px; background: #f8fafc; }
.search-icon { position: absolute; left: 16px; top: 50%; transform: translateY(-50%); color: var(--muted); }

/* Table Enhancements */
.payments-table-card { background: #fff; border: 1px solid var(--border); border-radius: 20px; overflow: hidden; }
.ref-code { font-family: 'JetBrains Mono', 'Fira Code', monospace; font-size: 13px; font-weight: 600; color: var(--primary); background: #f0f9ff; padding: 4px 8px; border-radius: 6px; }

/* Modal */
dialog { border: none; border-radius: 24px; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25); max-width: 480px; width: 90%; padding: 0; overflow: hidden; }
dialog::backdrop { background: rgba(15, 23, 42, 0.6); backdrop-filter: blur(8px); }
.modal-header { padding: 24px 32px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; background: #f8fafc; }
.modal-body { padding: 32px; }

@media(max-width:767px){
    .admin-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 16px;
    }
    .stats-grid {
        grid-template-columns: 1fr; /* Stack KPI cards on small screens */
    }
    .filter-form {
        flex-direction: column;
        align-items: stretch;
        gap: 16px;
    }
    .filter-form > div {
        width: 100%;
    }
    .filter-form button, .filter-form a.btn {
        width: 100%;
        justify-content: center;
    }
    .search-input-wrapper {
        min-width: unset; /* Remove min-width constraint */
    }
    .table-wrap { display: none; }
    .mobile-grid { display: grid; gap: 16px; grid-template-columns: 1fr; padding: 16px; }
}
@media(min-width:768px){
    .mobile-grid { display: none; }
}
</style>

<div class="admin-header">
    <h1 class="admin-title">Payment Approval</h1>
    <div style="display:flex; gap:12px">
        <a href="?export=csv&status=<?=e($status)?>&q=<?=e($search)?>" class="btn btn-outline" style="padding:10px 20px">
            <?=ui_icon('download', 18)?> Export CSV
        </a>
    </div>
</div>

<div class="stats-grid">
    <div class="stat-card stat-pending">
        <div class="stat-icon"><?=ui_icon('processing', 22)?></div>
        <div class="stat-info">
            <div class="stat-value"><?=number_format((int)$stats['pending'])?></div>
            <div class="stat-label">Pending Approval</div>
        </div>
    </div>
    <div class="stat-card stat-confirmed">
        <div class="stat-icon"><?=ui_icon('approved', 22)?></div>
        <div class="stat-info">
            <div class="stat-value"><?=number_format((int)$stats['confirmed'])?></div>
            <div class="stat-label">Confirmed</div>
        </div>
    </div>
    <div class="stat-card stat-rejected">
        <div class="stat-icon"><?=ui_icon('logout', 22)?></div>
        <div class="stat-info">
            <div class="stat-value"><?=number_format((int)$stats['rejected'])?></div>
            <div class="stat-label">Rejected</div>
        </div>
    </div>
    <div class="stat-card stat-volume">
        <div class="stat-icon">₦</div>
        <div class="stat-info">
            <div class="stat-value">₦<?=e(money((float)$stats['total_vol']))?></div>
            <div class="stat-label">Total Volume</div>
        </div>
    </div>
</div>

<div class="filter-card">
    <form method="get" class="filter-form">
        <div class="search-input-wrapper">
            <span class="search-icon"><?=ui_icon('faq', 18)?></span>
            <input type="text" name="q" class="search-input" placeholder="Search reference, user or email..." value="<?=e($search)?>">
        </div>
        <div style="min-width:160px">
            <select name="status" class="form-select" style="margin-bottom:0">
                <option value="">All Statuses</option>
                <option value="pending" <?=$status==='pending'?'selected':''?>>Pending</option>
                <option value="confirmed" <?=$status==='confirmed'?'selected':''?>>Confirmed</option>
                <option value="rejected" <?=$status==='rejected'?'selected':''?>>Rejected</option>
            </select>
        </div>
        <button class="btn primary" style="padding:12px 24px; font-weight:700">Filter Results</button>
        <?php if($status||$search): ?><a href="/admin/payments.php" class="btn" style="padding:12px">Reset</a><?php endif; ?>
    </form>
</div>

<div class="payments-table-card">
    <div class="table-wrap">
        <table class="striped">
            <thead>
                <tr>
                    <th style="padding-left:24px">Date & Time</th>
                    <th>User / Application</th>
                    <th>Reference</th>
                    <th>Amount</th>
                    <th>Method</th>
                    <th>Status</th>
                    <th style="padding-right:24px; text-align:right">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($payments as $p): ?>
                <tr>
                    <td style="padding-left:24px">
                        <div style="font-weight:600; font-size:14px"><?=date('M j, Y', strtotime($p['created_at']))?></div>
                        <div style="font-size:12px; color:var(--muted)"><?=date('H:i', strtotime($p['created_at']))?></div>
                    </td>
                    <td>
                        <div style="font-weight:700; color:var(--text)"><?=e($p['full_name'])?></div>
                        <div style="font-size:12px; color:var(--muted)"><?=e($p['service_name'])?> (#<?=e((string)$p['application_id'])?>)</div>
                    </td>
                    <td><span class="ref-code"><?=e($p['payment_reference'])?></span></td>
                    <td><div style="font-weight:800; color:var(--text); font-size:16px">₦<?=number_format((float)$p['amount'])?></div></td>
                    <td>
                        <span class="badge" style="font-size:11px; font-weight:700"><?=e(strtoupper($p['method'] ?? 'bank'))?></span>
                        <?php if (!empty($p['receipt_path'])): ?>
                            <div style="margin-top:4px">
                                <a href="<?=e($p['receipt_path'])?>" target="_blank" class="badge" style="background:#fef3c7; color:#d97706; text-decoration:none; border:1px solid #fcd34d">
                                    <?=ui_icon('open', 10)?> View Receipt
                                </a>
                            </div>
                        <?php endif; ?>
                    </td>
                    <td>

                        <?php 
                        $st = $p['status'];
                        $cls = 'status-submitted'; // blue-ish
                        if($st=='confirmed') $cls='status-approved'; // green
                        if($st=='rejected') $cls='status-rejected'; // red
                        ?>
                        <span class="status-pill <?=$cls?>"><?=ucfirst($st)?></span>
                    </td>
                    <td style="padding-right:24px; text-align:right">
                        <?php if($p['status'] === 'pending'): ?>
                        <div style="display:flex; gap:8px; justify-content:flex-end">
                            <button class="btn primary" style="padding:8px 14px; font-size:13px; font-weight:700" 
                                    onclick="openPaymentModal('approve', <?=e((string)$p['id'])?>, '<?=e($p['payment_reference'])?>')">Approve</button>
                            <button class="btn" style="padding:8px 14px; font-size:13px; font-weight:700; color:#ef4444; border-color:#fecaca" 
                                    onclick="openPaymentModal('reject', <?=e((string)$p['id'])?>, '<?=e($p['payment_reference'])?>')">Reject</button>
                        </div>
                        <?php else: ?>
                        <span style="font-size:12px; font-weight:600; color:var(--muted); background:#f1f5f9; padding:4px 10px; border-radius:6px">Processed</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($payments)): ?>
                <tr><td colspan="7" style="text-align:center; padding:60px; color:var(--muted)">No payments found matching your criteria.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <?php if ($totalPages > 1): ?>
    <div style="display:flex; justify-content:center; gap:8px; padding:24px; border-top:1px solid var(--border)">
        <?php for($i=1; $i<=$totalPages; $i++): ?>
            <a href="?page=<?=$i?>&status=<?=e($status)?>&q=<?=e($search)?>" class="btn <?=$i===$page?'primary':''?>" style="padding:8px 16px; min-width:44px; text-align:center"><?=$i?></a>
        <?php endfor; ?>
    </div>
    <?php endif; ?>

    <div class="mobile-grid">
        <?php foreach ($payments as $p): ?>
            <?php 
            $st = $p['status'];
            $cls = 'status-submitted'; // blue-ish
            if($st=='confirmed') $cls='status-approved'; // green
            if($st=='rejected') $cls='status-rejected'; // red
            ?>
            <div class="card" style="margin-bottom:0; padding:20px; border-radius:16px">
                <div style="display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:16px">
                    <div>
                        <div style="font-weight:700; color:var(--text)"><?=e($p['full_name'])?></div>
                        <div style="font-size:13px; color:var(--muted)"><?=e($p['service_name'])?> (#<?=e((string)$p['application_id'])?>)</div>
                    </div>
                    <span class="status-pill <?=$cls?>"><?=ucfirst($st)?></span>
                </div>
                <div style="font-size:13px; color:var(--muted); margin-bottom:4px">Ref: <span class="ref-code" style="background:none; padding:0"><?=e($p['payment_reference'])?></span></div>
                <div style="font-size:13px; color:var(--muted); margin-bottom:16px">Method: <span class="badge" style="font-size:11px; font-weight:700"><?=e(strtoupper($p['method'] ?? 'bank'))?></span></div>
                <div style="display:flex; justify-content:space-between; align-items:center; margin-top:8px; border-top:1px solid #f1f5f9; padding-top:12px">
                    <div style="font-weight:800; color:var(--text); font-size:16px">₦<?=number_format((float)$p['amount'])?></div>
                    <?php if($p['status'] === 'pending'): ?>
                    <div style="display:flex; gap:8px;">
                        <button class="btn primary" style="padding:6px 12px; font-size:12px; font-weight:700" 
                                onclick="openPaymentModal('approve', <?=e((string)$p['id'])?>, '<?=e($p['payment_reference'])?>')">Approve</button>
                        <button class="btn" style="padding:6px 12px; font-size:12px; font-weight:700; color:#ef4444; border-color:#fecaca" 
                                onclick="openPaymentModal('reject', <?=e((string)$p['id'])?>, '<?=e($p['payment_reference'])?>')">Reject</button>
                    </div>
                    <?php else: ?>
                    <span style="font-size:12px; font-weight:600; color:var(--muted); background:#f1f5f9; padding:4px 10px; border-radius:6px">Processed</span>
                    <?php endif; ?>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>
</div>

<!-- Modal Dialog -->
<dialog id="payment-modal">
    <div class="modal-header">
        <h3 style="margin:0; font-size:18px; font-weight:800" id="modal-title">Approve Payment</h3>
        <button onclick="document.getElementById('payment-modal').close()" style="background:none; border:none; font-size:28px; cursor:pointer; color:var(--muted)">&times;</button>
    </div>
    <div class="modal-body">
        <p id="modal-desc" style="font-size:14px; color:var(--muted); margin-bottom:24px">Are you sure you want to approve this payment?</p>
        <form method="post" id="payment-form">
            <?=csrf_field()?>
            <input type="hidden" name="action" id="modal-action">
            <input type="hidden" name="payment_id" id="modal-id">
            
            <div class="form-group">
                <label class="form-label">Internal Admin Note (Audit Trail)</label>
                <textarea name="admin_note" class="form-textarea" required rows="3" placeholder="Reason for approval or rejection..."></textarea>
            </div>
            
            <div style="display:flex; gap:12px; margin-top:32px">
                <button type="button" class="btn btn-outline" style="flex:1" onclick="document.getElementById('payment-modal').close()">Cancel</button>
                <button type="submit" class="btn primary" style="flex:1.5; font-weight:700" id="modal-btn">Confirm Approval</button>
            </div>
        </form>
    </div>
</dialog>

<script>
function openPaymentModal(action, id, ref) {
    const modal = document.getElementById('payment-modal');
    const title = document.getElementById('modal-title');
    const desc = document.getElementById('modal-desc');
    const actInput = document.getElementById('modal-action');
    const idInput = document.getElementById('modal-id');
    const btn = document.getElementById('modal-btn');
    
    actInput.value = action;
    idInput.value = id;
    
    if (action === 'approve') {
        title.textContent = 'Approve Payment';
        desc.textContent = 'Confirming approval for reference: ' + ref;
        btn.textContent = 'Approve Payment';
        btn.style.background = 'var(--primary)';
        btn.style.borderColor = 'var(--primary)';
        btn.style.color = '#fff';
    } else {
        title.textContent = 'Reject Payment';
        desc.textContent = 'Confirming rejection for reference: ' + ref;
        btn.textContent = 'Reject Payment';
        btn.style.background = '#ef4444';
        btn.style.borderColor = '#ef4444';
        btn.style.color = '#fff';
    }
    
    modal.showModal();
}

document.getElementById('payment-modal').onclick = (e) => {
    if(e.target === document.getElementById('payment-modal')) document.getElementById('payment-modal').close();
};
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
