<?php include "header.php"; ?>
<?php
// Handle Verification
if (isset($_POST['verify_kyc'])) {
    $mb = mysqli_real_escape_string($conn, $_POST['mobileno']);
    $update = "UPDATE `users` SET `aadhar_kyc` = '1' WHERE mobile='$mb'";
    $rpt = mysqli_query($conn, $update);

    if ($rpt) {
        // Success Alert
        echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';
        echo '<script>
            Swal.fire({
                icon: "success",
                title: "KYC Verified Successfully!!",
                showConfirmButton: true,
                confirmButtonText: "Ok!"
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = "manage_kyc";
                }
            });
        </script>';
        exit;
    } else {
        // Error Alert
        echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';
        echo '<script>
            Swal.fire({
                icon: "error",
                title: "KYC Verification Failed!!",
                showConfirmButton: true,
                confirmButtonText: "Ok!"
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = "manage_kyc";
                }
            });
        </script>';
        exit;
    }
}

$perms = isset($userdata['sidebar_permissions']) ? json_decode($userdata['sidebar_permissions'], true) : [];
if ($userdata["role"] != 'Admin' && (!is_array($perms) || !in_array('manage_kyc', $perms))) {
    echo '<script>window.location.href = "dashboard";</script>';
    exit;
}
?>
<?php
// Ensure table exists to prevent errors
$checkTable = mysqli_query($conn, "SHOW TABLES LIKE 'kyc_documents'");
if (mysqli_num_rows($checkTable) == 0) {
    $createTable = "CREATE TABLE kyc_documents (
        id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        user_id INT(11) NOT NULL,
        full_name VARCHAR(255) NOT NULL,
        aadhaar_number VARCHAR(20) NOT NULL,
        dob DATE NOT NULL,
        aadhaar_image VARCHAR(255) NOT NULL,
        status ENUM('Pending', 'Approved', 'Rejected') DEFAULT 'Pending',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )";
    mysqli_query($conn, $createTable);
}
?>

<main class="app-content">
    <div class="app-title">
        <div>
            <h1><i class="fa fa-id-card"></i> KYC Management</h1>
        </div>
        <ul class="app-breadcrumb breadcrumb">
            <li class="breadcrumb-item"><i class="fa fa-home fa-lg"></i></li>
            <li class="breadcrumb-item"><a href="dashboard">Dashboard</a></li>
        </ul>
    </div>
    <div class="tile mb-4">
        <div class="page-header">
            <div class="row">
                <div class="col-lg-12">
                    <div class="table-responsive">
                        <table class="table table-sm table-hover table-bordered table-head-bg-primary" id="dataTable" width="100%">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>User Name</th>
                                    <th>Mobile No</th>
                                    <th>Aadhaar No</th>
                                    <th>KYC Details</th>
                                    <th>Image</th>
                                    <th>Status</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                // Handle Approve/Reject
                                if (isset($_POST['process_kyc'])) {
                                    $kyc_id = mysqli_real_escape_string($conn, $_POST['kyc_id']);
                                    $action_type = $_POST['process_kyc']; // 'approve' or 'reject'
                                    
                                    // Fetch kyc record
                                    $fetch_kyc = mysqli_query($conn, "SELECT * FROM kyc_documents WHERE id = '$kyc_id'");
                                    if (mysqli_num_rows($fetch_kyc) > 0) {
                                        $kyc_data = mysqli_fetch_assoc($fetch_kyc);
                                        $u_id = $kyc_data['user_id'];
                                        
                                        if ($action_type == 'approve') {
                                            $updateKyc = mysqli_query($conn, "UPDATE kyc_documents SET status = 'Approved' WHERE id = '$kyc_id'");
                                            $updateUser = mysqli_query($conn, "UPDATE users SET aadhar_kyc = '1' WHERE id = '$u_id'");
                                            
                                            // Optional: Move uploaded file to a more permanent/secure location or rename if needed
                                            
                                            if ($updateKyc && $updateUser) {
                                                echo "<script>Swal.fire({icon: 'success', title: 'KYC Approved!', text: 'User is now verified.'}).then(() => { window.location.href='manage_kyc'; });</script>";
                                            } else {
                                                echo "<script>Swal.fire({icon: 'error', title: 'Error!', text: 'Database update failed.'});</script>";
                                            }
                                            
                                        } else if ($action_type == 'reject') {
                                            $updateKyc = mysqli_query($conn, "UPDATE kyc_documents SET status = 'Rejected' WHERE id = '$kyc_id'");
                                            // Send notification ideally
                                            if ($updateKyc) {
                                                echo "<script>Swal.fire({icon: 'info', title: 'KYC Rejected', text: 'User request has been rejected.'}).then(() => { window.location.href='manage_kyc'; });</script>";
                                            }
                                        }
                                    }
                                }

                                // Query to fetch Pending/All KYC requests
                                // We join with users to get mobile number and registered name
                                $query = "SELECT k.*, u.mobile, u.name as user_name FROM kyc_documents k JOIN users u ON k.user_id = u.id ORDER BY k.created_at DESC";
                                $query_run = mysqli_query($conn, $query);

                                if ($query_run) {
                                    while ($row = mysqli_fetch_assoc($query_run)) {
                                        echo "<tr>";
                                        echo "<td>" . htmlspecialchars($row['id']) . "</td>";
                                        echo "<td>" . htmlspecialchars($row['user_name']) . "</td>";
                                        echo "<td>" . htmlspecialchars($row['mobile']) . "</td>";
                                        echo "<td>" . htmlspecialchars($row['aadhaar_number']) . "</td>";
                                        echo "<td>" . htmlspecialchars($row['full_name']) . "<br><small>" . htmlspecialchars($row['dob']) . "</small></td>";
                                        
                                        // Image Link
                                        $img_path = "assets/kyc_docs/" . htmlspecialchars($row['aadhaar_image']);
                                        echo "<td><a href='$img_path' target='_blank' class='btn btn-info btn-sm'>View Image</a></td>";
                                        
                                        // Status Badge
                                        $status_label = '';
                                        if ($row['status'] == 'Approved') $status_label = '<span class="badge badge-success">Approved</span>';
                                        elseif ($row['status'] == 'Rejected') $status_label = '<span class="badge badge-danger">Rejected</span>';
                                        else $status_label = '<span class="badge badge-warning text-dark">Pending</span>';
                                        
                                        echo "<td>" . $status_label . "</td>";
                                        
                                        echo "<td>";
                                        if ($row['status'] == 'Pending') {
                                            echo '<form action="" method="POST" style="display:inline-block; margin-right:5px;">
                                                    <input type="hidden" name="kyc_id" value="' . $row['id'] . '">
                                                    <button class="btn btn-success btn-sm" name="process_kyc" value="approve">Approve</button>
                                                  </form>';
                                                  
                                            echo '<form action="" method="POST" style="display:inline-block;">
                                                    <input type="hidden" name="kyc_id" value="' . $row['id'] . '">
                                                    <button class="btn btn-danger btn-sm" name="process_kyc" value="reject">Reject</button>
                                                  </form>';
                                        } else {
                                            echo "Processed";
                                        }
                                        echo "</td>";
                                        echo "</tr>";
                                    }
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<!-- Essential javascripts -->
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/popper.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/main.js"></script>
<script src="js/plugins/pace.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.1/css/dataTables.bootstrap5.min.css"/>
<script src="https://cdn.datatables.net/1.13.1/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.1/js/dataTables.bootstrap5.min.js"></script>
<script>
    $(document).ready(function () {
        $("#dataTable").DataTable();
    });
</script>
