<?php
define('SECURE_ACCESS', true);

$pageTitle = "KYC Approvals";
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

requireAdmin();
$currentUser = getCurrentUser();

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

// Handle KYC & Bank Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
        header("Location: kyc_approvals");
        exit();
    }

    if (isset($_POST['action']) && isset($_POST['kyc_id'])) {
        $kycId = (int)$_POST['kyc_id'];
        $action = $_POST['action'];
        
        try {
            $stmt_get_user = $pdo->prepare("SELECT user_id FROM kyc_records WHERE id = ?");
            $stmt_get_user->execute([$kycId]);
            $target_user_id = $stmt_get_user->fetchColumn();

            require_once __DIR__ . '/../../includes/notification_helper.php';

            if ($action === 'approve_doc1') {
                $stmt = $pdo->prepare("UPDATE kyc_records SET doc1_status = 'approved', updated_at = CURRENT_TIMESTAMP WHERE id = ?");
                $stmt->execute([$kycId]);
                $_SESSION['flash_success'] = "Photo ID approved successfully.";
                sendMultichannelNotification($target_user_id, 'kyc_status', ['status' => 'Photo ID Approved']);
            } elseif ($action === 'reject_doc1') {
                $stmt = $pdo->prepare("UPDATE kyc_records SET doc1_status = 'rejected', updated_at = CURRENT_TIMESTAMP WHERE id = ?");
                $stmt->execute([$kycId]);
                $_SESSION['flash_success'] = "Photo ID rejected.";
                sendMultichannelNotification($target_user_id, 'kyc_status', ['status' => 'Photo ID Rejected']);
            } elseif ($action === 'approve_doc2') {
                $stmt = $pdo->prepare("UPDATE kyc_records SET doc2_status = 'approved', updated_at = CURRENT_TIMESTAMP WHERE id = ?");
                $stmt->execute([$kycId]);
                $_SESSION['flash_success'] = "Address Proof approved successfully.";
                sendMultichannelNotification($target_user_id, 'kyc_status', ['status' => 'Address Proof Approved']);
            } elseif ($action === 'reject_doc2') {
                $stmt = $pdo->prepare("UPDATE kyc_records SET doc2_status = 'rejected', updated_at = CURRENT_TIMESTAMP WHERE id = ?");
                $stmt->execute([$kycId]);
                $_SESSION['flash_success'] = "Address Proof rejected.";
                sendMultichannelNotification($target_user_id, 'kyc_status', ['status' => 'Address Proof Rejected']);
            } elseif ($action === 'approve_bank') {
                $stmt = $pdo->prepare("UPDATE kyc_records SET bank_status = 'verified', updated_at = CURRENT_TIMESTAMP WHERE id = ?");
                $stmt->execute([$kycId]);
                $_SESSION['flash_success'] = "Bank Account details approved successfully.";
                sendMultichannelNotification($target_user_id, 'kyc_status', ['status' => 'Bank Details Verified']);
            } elseif ($action === 'reject_bank') {
                $stmt = $pdo->prepare("UPDATE kyc_records SET bank_status = 'rejected', updated_at = CURRENT_TIMESTAMP WHERE id = ?");
                $stmt->execute([$kycId]);
                $_SESSION['flash_success'] = "Bank Account details rejected.";
                sendMultichannelNotification($target_user_id, 'kyc_status', ['status' => 'Bank Details Rejected']);
            }
        } catch (PDOException $e) {
            $_SESSION['flash_error'] = "Action failed: " . $e->getMessage();
        }
        header("Location: kyc_approvals");
        exit();
    }
}

// Fetch filter option
$filter_status = $_GET['status'] ?? 'all';

// Fetch KYC submissions
$kyc_records = [];
$pending_count = 0;
$total_records = 0;
$total_pages = 0;
$limit = 15;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $limit;

try {
    // 1. Build Count Query
    $count_query = "SELECT COUNT(*) FROM kyc_records k JOIN users u ON k.user_id = u.id";
    $where_clause = "";
    if ($filter_status === 'pending') {
        $where_clause = " WHERE k.doc1_status = 'pending' OR k.doc2_status = 'pending' OR k.bank_status = 'initiated' ";
    } elseif ($filter_status === 'approved') {
        $where_clause = " WHERE k.doc1_status = 'approved' AND k.doc2_status = 'approved' AND k.bank_status = 'verified' ";
    } elseif ($filter_status === 'rejected') {
        $where_clause = " WHERE k.doc1_status = 'rejected' OR k.doc2_status = 'rejected' OR k.bank_status = 'rejected' ";
    }
    
    $stmt_c = $pdo->query($count_query . $where_clause);
    $total_records = (int)$stmt_c->fetchColumn() ?: 0;
    $total_pages = ceil($total_records / $limit);

    // 2. Build Paginated Query
    $query = "
        SELECT k.*, u.username, u.email 
        FROM kyc_records k 
        JOIN users u ON k.user_id = u.id 
    " . $where_clause . " ORDER BY k.updated_at DESC LIMIT $limit OFFSET $offset";
    
    $stmt = $pdo->query($query);
    $kyc_records = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Get total pending counts for count badge
    $stmt_p = $pdo->query("
        SELECT COUNT(*) 
        FROM kyc_records 
        WHERE doc1_status = 'pending' OR doc2_status = 'pending' OR bank_status = 'initiated'
    ");
    $pending_count = $stmt_p->fetchColumn();

} catch (PDOException $e) {
    $error = "Error querying records: " . $e->getMessage();
}

$prefix = '../';
require_once __DIR__ . '/../../includes/header.php';
?>

    <div class="row" style="margin-top: 75px;">
        <div class="col-12">
            <!-- Page Title Header -->
            <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3 mb-4 mt-2">
                <div>
                    <h1 class="h2 fw-bold text-dark mb-1">KYC Approvals</h1>
                    <p class="text-muted mb-0">Manage customer compliance records, verification documents, and bank account settings.</p>
                </div>
            </div>

            <!-- Alerts -->
            <?php if (isset($_SESSION['flash_success'])): ?>
                <div class="alert alert-success alert-dismissible fade show border-0 shadow-sm" role="alert">
                    <i class="bi bi-check-circle-fill me-2"></i>
                    <?php echo htmlspecialchars($_SESSION['flash_success']); unset($_SESSION['flash_success']); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>

            <?php if (isset($_SESSION['flash_error'])): ?>
                <div class="alert alert-danger alert-dismissible fade show border-0 shadow-sm" role="alert">
                    <i class="bi bi-exclamation-triangle-fill me-2"></i>
                    <?php echo htmlspecialchars($_SESSION['flash_error']); unset($_SESSION['flash_error']); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>

            <?php if (!empty($error)): ?>
                <div class="alert alert-danger border-0 shadow-sm" role="alert">
                    <i class="bi bi-exclamation-circle-fill me-2"></i>
                    <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>

            <!-- Page Header Card -->
            <div class="card border-0 shadow-sm mb-4 rounded-3 overflow-hidden">
                <div class="card-header bg-white border-bottom py-3 d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3">
                    <div class="d-flex align-items-center">
                        <div class="bg-info-subtle text-info p-2.5 rounded-3 me-3">
                            <i class="bi bi-shield-fill-check fs-4"></i>
                        </div>
                        <div>
                            <h5 class="mb-0 fw-bold text-dark">KYC & Banking Verification approvals</h5>
                            <p class="text-muted small mb-0">Inspect and approve member identification documents and bank payout settings.</p>
                        </div>
                    </div>

                    <!-- Filter Options -->
                    <div class="btn-group btn-group-sm shadow-sm" role="group" aria-label="KYC Filters">
                        <a href="kyc_approvals?status=all" class="btn btn-outline-secondary px-3 fw-semibold <?php echo $filter_status === 'all' ? 'active' : ''; ?>">All Submissions</a>
                        <a href="kyc_approvals?status=pending" class="btn btn-outline-secondary px-3 fw-semibold position-relative <?php echo $filter_status === 'pending' ? 'active' : ''; ?>">
                            Pending Requests
                            <?php if ($pending_count > 0): ?>
                                <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger border border-white" style="font-size: 0.65rem;">
                                    <?php echo $pending_count; ?>
                                </span>
                            <?php endif; ?>
                        </a>
                        <a href="kyc_approvals?status=approved" class="btn btn-outline-secondary px-3 fw-semibold <?php echo $filter_status === 'approved' ? 'active' : ''; ?>">Approved</a>
                        <a href="kyc_approvals?status=rejected" class="btn btn-outline-secondary px-3 fw-semibold <?php echo $filter_status === 'rejected' ? 'active' : ''; ?>">Rejected</a>
                    </div>
                </div>

                <!-- Card Body (Table View) -->
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0" style="font-size: 0.9rem;">
                            <thead class="table-light text-muted uppercase font-monospace" style="font-size: 0.75rem;">
                                <tr>
                                    <th class="ps-4">User Info</th>
                                    <th>Photo Identification</th>
                                    <th>Address Verification</th>
                                    <th>Bank Account Details</th>
                                    <th>Last Updated</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($kyc_records)): ?>
                                    <tr>
                                        <td colspan="5" class="text-center py-5 text-muted">
                                            <i class="bi bi-shield-slash fs-1 mb-2 d-block text-secondary"></i>
                                            <p class="mb-0 fw-semibold">No KYC submissions matching filter criteria.</p>
                                        </td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($kyc_records as $kr): ?>
                                        <tr>
                                            <!-- User Info -->
                                            <td class="ps-4">
                                                <strong class="text-dark d-block"><?php echo htmlspecialchars($kr['username']); ?></strong>
                                                <span class="text-muted small font-monospace"><?php echo htmlspecialchars($kr['email']); ?></span>
                                            </td>

                                            <!-- Document 1: Photo ID -->
                                            <td>
                                                <div class="mb-1">
                                                    <span class="badge <?php 
                                                        if ($kr['doc1_status'] === 'approved') echo 'bg-success';
                                                        elseif ($kr['doc1_status'] === 'rejected') echo 'bg-danger';
                                                        else echo 'bg-warning text-dark';
                                                    ?> text-uppercase small" style="font-size: 0.7rem;"><?php echo $kr['doc1_status']; ?></span>
                                                    <span class="text-secondary small ms-1">(<?php echo htmlspecialchars(ucfirst($kr['doc1_type'])); ?>)</span>
                                                </div>
                                                
                                                <?php if (!empty($kr['doc1_number'])): ?>
                                                    <div class="small text-dark font-monospace mb-1" style="font-size: 0.8rem;">No: <?php echo htmlspecialchars($kr['doc1_number']); ?></div>
                                                <?php endif; ?>

                                                <?php if (!empty($kr['doc1_file'])): ?>
                                                    <a href="../download/<?php echo urlencode(basename($kr['doc1_file'])); ?>" target="_blank" class="btn btn-sm btn-outline-secondary py-0.5 px-2 mb-2" style="font-size: 0.75rem;">
                                                        <i class="bi bi-file-earmark-arrow-down me-1"></i>View Document
                                                    </a>
                                                <?php endif; ?>

                                                <?php if ($kr['doc1_status'] === 'pending'): ?>
                                                    <div class="d-flex gap-1 mt-1">
                                                        <form method="POST" action="kyc_approvals" class="d-inline">
                                                            <input type="hidden" name="action" value="approve_doc1">
                                                            <input type="hidden" name="kyc_id" value="<?php echo $kr['id']; ?>">
                                                            <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                                                            <button type="submit" class="btn btn-xs btn-success text-white py-0.5 px-2" style="font-size: 0.7rem;" title="Approve">
                                                                <i class="bi bi-check-lg"></i> Approve
                                                            </button>
                                                        </form>
                                                        <form method="POST" action="kyc_approvals" class="d-inline" onsubmit="return confirm('Reject Photo ID?');">
                                                            <input type="hidden" name="action" value="reject_doc1">
                                                            <input type="hidden" name="kyc_id" value="<?php echo $kr['id']; ?>">
                                                            <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                                                            <button type="submit" class="btn btn-xs btn-danger text-white py-0.5 px-2" style="font-size: 0.7rem;" title="Reject">
                                                                <i class="bi bi-x-lg"></i> Reject
                                                            </button>
                                                        </form>
                                                    </div>
                                                <?php endif; ?>
                                            </td>

                                            <!-- Document 2: Address Proof -->
                                            <td>
                                                <div class="mb-1">
                                                    <span class="badge <?php 
                                                        if ($kr['doc2_status'] === 'approved') echo 'bg-success';
                                                        elseif ($kr['doc2_status'] === 'rejected') echo 'bg-danger';
                                                        else echo 'bg-warning text-dark';
                                                    ?> text-uppercase small" style="font-size: 0.7rem;"><?php echo $kr['doc2_status']; ?></span>
                                                    <span class="text-secondary small ms-1">(<?php echo htmlspecialchars(ucfirst($kr['doc2_type'])); ?>)</span>
                                                </div>

                                                <?php if (!empty($kr['doc2_number'])): ?>
                                                    <div class="small text-dark font-monospace mb-1" style="font-size: 0.8rem;">No: <?php echo htmlspecialchars($kr['doc2_number']); ?></div>
                                                <?php endif; ?>

                                                <?php if (!empty($kr['doc2_file'])): ?>
                                                    <a href="../download/<?php echo urlencode(basename($kr['doc2_file'])); ?>" target="_blank" class="btn btn-sm btn-outline-secondary py-0.5 px-2 mb-2" style="font-size: 0.75rem;">
                                                        <i class="bi bi-file-earmark-arrow-down me-1"></i>View Document
                                                    </a>
                                                <?php endif; ?>

                                                <?php if ($kr['doc2_status'] === 'pending'): ?>
                                                    <div class="d-flex gap-1 mt-1">
                                                        <form method="POST" action="kyc_approvals" class="d-inline">
                                                            <input type="hidden" name="action" value="approve_doc2">
                                                            <input type="hidden" name="kyc_id" value="<?php echo $kr['id']; ?>">
                                                            <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                                                            <button type="submit" class="btn btn-xs btn-success text-white py-0.5 px-2" style="font-size: 0.7rem;" title="Approve">
                                                                <i class="bi bi-check-lg"></i> Approve
                                                            </button>
                                                        </form>
                                                        <form method="POST" action="kyc_approvals" class="d-inline" onsubmit="return confirm('Reject Address Proof?');">
                                                            <input type="hidden" name="action" value="reject_doc2">
                                                            <input type="hidden" name="kyc_id" value="<?php echo $kr['id']; ?>">
                                                            <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                                                            <button type="submit" class="btn btn-xs btn-danger text-white py-0.5 px-2" style="font-size: 0.7rem;" title="Reject">
                                                                <i class="bi bi-x-lg"></i> Reject
                                                            </button>
                                                        </form>
                                                    </div>
                                                <?php endif; ?>
                                            </td>

                                            <!-- Bank Account Details & Status -->
                                            <td>
                                                <div class="mb-1">
                                                    <span class="badge <?php 
                                                        if ($kr['bank_status'] === 'verified') echo 'bg-success';
                                                        elseif ($kr['bank_status'] === 'initiated') echo 'bg-warning text-dark';
                                                        elseif ($kr['bank_status'] === 'rejected') echo 'bg-danger';
                                                        else echo 'bg-secondary';
                                                    ?> text-uppercase small" style="font-size: 0.7rem;"><?php echo $kr['bank_status']; ?></span>
                                                </div>

                                                <?php if (!empty($kr['bank_name'])): ?>
                                                    <div class="text-dark small border rounded p-2 bg-light font-monospace" style="font-size: 0.8rem; line-height: 1.35;">
                                                        <strong class="d-block text-secondary small"><?php echo htmlspecialchars($kr['bank_name']); ?></strong>
                                                        <span>Holder: <?php echo htmlspecialchars($kr['account_holder']); ?></span><br>
                                                        <span>AcNo: *<?php echo htmlspecialchars(substr($kr['account_number'], -4)); ?></span><br>
                                                        <span>IFSC: <?php echo htmlspecialchars($kr['routing_number']); ?></span>
                                                    </div>
                                                    
                                                    <?php if ($kr['bank_status'] === 'initiated'): ?>
                                                        <div class="d-flex gap-1 mt-1.5">
                                                            <form method="POST" action="kyc_approvals" class="d-inline">
                                                                <input type="hidden" name="action" value="approve_bank">
                                                                <input type="hidden" name="kyc_id" value="<?php echo $kr['id']; ?>">
                                                                <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                                                                <button type="submit" class="btn btn-xs btn-success text-white py-0.5 px-2" style="font-size: 0.7rem;" title="Approve Bank">
                                                                    <i class="bi bi-check-lg"></i> Verify Bank
                                                                </button>
                                                            </form>
                                                            <form method="POST" action="kyc_approvals" class="d-inline" onsubmit="return confirm('Reject Bank Account?');">
                                                                <input type="hidden" name="action" value="reject_bank">
                                                                <input type="hidden" name="kyc_id" value="<?php echo $kr['id']; ?>">
                                                                <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                                                                <button type="submit" class="btn btn-xs btn-danger text-white py-0.5 px-2" style="font-size: 0.7rem;" title="Reject Bank">
                                                                    <i class="bi bi-x-lg"></i> Reject Bank
                                                                </button>
                                                            </form>
                                                        </div>
                                                    <?php endif; ?>
                                                <?php else: ?>
                                                    <span class="text-muted small">Not submitted</span>
                                                <?php endif; ?>
                                            </td>

                                            <!-- Timestamp -->
                                            <td>
                                                <span class="text-muted font-monospace small d-block"><?php echo date('Y-m-d H:i', strtotime($kr['updated_at'])); ?></span>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                <?php if ($total_pages > 1): ?>
                    <div class="card-footer bg-light border-top py-3 d-flex flex-column flex-md-row justify-content-between align-items-center gap-3">
                        <div class="small text-secondary font-monospace">
                            Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $limit, $total_records); ?> of <?php echo $total_records; ?> submissions
                        </div>
                        <nav aria-label="Page navigation">
                            <ul class="pagination pagination-sm mb-0 align-items-center gap-1">
                                <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => 1])); ?>">First</a>
                                </li>
                                <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>">Previous</a>
                                </li>
                                <li class="page-item disabled mx-1">
                                    <span class="text-secondary small fw-bold" style="font-size: 0.75rem;">Page <?php echo $page; ?> of <?php echo $total_pages; ?></span>
                                </li>
                                <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>">Next</a>
                                </li>
                                <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $total_pages])); ?>">Last</a>
                                </li>
                            </ul>
                        </nav>
                    </div>
                <?php endif; ?>
            </div>

        </div>
    </div>

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