<?php include "header.php"; ?>
<?php
if (isset($_POST['delete'])) {
    $mb = mysqli_real_escape_string($conn,$_POST['mobileno']);
    $del = "DELETE FROM `users` WHERE mobile='$mb'";
    $rpt = mysqli_query($conn, $del);

    if ($rpt) {
        // Show SweetAlert2 success message
        echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';
        echo '<script>
    Swal.fire({
        icon: "success",
        title: "User Deleted Successfully!!",
        showConfirmButton: true,
        confirmButtonText: "Ok!",
        allowOutsideClick: false,
        allowEscapeKey: false
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = "merchant_list";
        }
    });
</script>';
        exit;
    } else {
        // Show SweetAlert2 error message
        echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';
        echo '<script>
    Swal.fire({
        icon: "error",
        title: "User Delete Failure!!",
        showConfirmButton: true,
        confirmButtonText: "Ok!",
        allowOutsideClick: false,
        allowEscapeKey: false
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = "merchant_list";
        }
    });
</script>';
        exit;
    }
}

if ($userdata["role"] != 'Admin') {
    echo '<script>
 window.location.href = "dashboard";
</script>';
    exit;
}

// ---- Pull all merchants once so we can render both the summary chips
// and the table/card list from the same result set. ----
$merchants = [];
$query = "SELECT `id`, `name`, `mobile`, `role`, `password`, `company`, `pin`, `pan`, `aadhaar`, `location`, `user_token`, `expiry`, `callback_url` FROM `users` WHERE role='User'";
$query_run = mysqli_query($conn, $query);
if ($query_run) {
    while ($row = mysqli_fetch_assoc($query_run)) {
        $merchants[] = $row;
    }
}

$today = date('Y-m-d');
$totalMerchants = count($merchants);
$activeCount = 0; $expiringCount = 0; $expiredCount = 0;
foreach ($merchants as $m) {
    $exp = $m['expiry'] ?? null;
    if (!$exp) { $activeCount++; continue; }
    $days = (strtotime($exp) - strtotime($today)) / 86400;
    if ($days < 0) { $expiredCount++; }
    elseif ($days <= 7) { $expiringCount++; }
    else { $activeCount++; }
}

function maskMiddle($val, $keepStart = 2, $keepEnd = 2) {
    $val = (string)$val;
    $len = strlen($val);
    if ($len <= $keepStart + $keepEnd) return $val;
    return substr($val, 0, $keepStart) . str_repeat('•', max(3, $len - $keepStart - $keepEnd)) . substr($val, -$keepEnd);
}
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=JetBrains+Mono:wght@400;600&display=swap" rel="stylesheet">
<link href="./assets/vendors/DataTables/datatables.min.css" rel="stylesheet" />

<style>
    :root{
        --p:#6c63ff; --p2:#e040fb;
        --g: linear-gradient(135deg,#6c63ff,#e040fb);
        --success:#43e97b; --danger:#ff6584; --warning:#f5b93b; --info:#3ea6ff;
    }
    *{box-sizing:border-box}
    html, body, .content-wrapper{ background:#0a0a12 !important; }
    body{ font-family:'Inter',sans-serif; color:#fff; }
    .content-wrapper{min-height:100vh}
    ::-webkit-scrollbar{width:8px;height:8px}
    ::-webkit-scrollbar-track{background:transparent}
    ::-webkit-scrollbar-thumb{background:rgba(255,255,255,.12);border-radius:10px}

    .mw-wrap{padding:20px;max-width:1440px;margin:0 auto;animation:pageIn .4s ease both}
    @keyframes pageIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}

    .mw-head{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:14px;margin-bottom:22px}
    .mw-head h1{font-size:1.55rem;font-weight:800;margin:0;color:#fff;display:flex;align-items:center;gap:10px}
    .mw-head h1 .icn{
        width:38px;height:38px;border-radius:12px;background:var(--g);display:inline-flex;
        align-items:center;justify-content:center;font-size:16px;box-shadow:0 6px 18px rgba(108,99,255,.35);
    }
    .mw-head p{font-size:.85rem;color:rgba(255,255,255,.45);margin:4px 0 0 48px}

    .btn-ghost{
        background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);color:#fff;
        padding:9px 16px;border-radius:10px;font-size:.82rem;font-weight:600;cursor:pointer;
        display:inline-flex;align-items:center;gap:7px;transition:.2s;text-decoration:none;
    }
    .btn-ghost:hover{background:rgba(255,255,255,.1);border-color:rgba(255,255,255,.2);color:#fff;transform:translateY(-1px)}
    .btn-primary-cta{
        background:var(--g);border:none;color:#fff;padding:9px 16px;border-radius:10px;
        font-size:.82rem;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:7px;
        transition:.2s;box-shadow:0 6px 18px rgba(108,99,255,.3);text-decoration:none;
    }
    .btn-primary-cta:hover{transform:translateY(-1px);box-shadow:0 10px 24px rgba(108,99,255,.45);color:#fff}

    .mini-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:22px}
    .mini-card{
        background:rgba(255,255,255,.04);backdrop-filter:blur(20px);
        border:1px solid rgba(255,255,255,.08);border-radius:16px;padding:16px 18px;
        display:flex;align-items:center;gap:12px;transition:.25s;
    }
    .mini-card:hover{transform:translateY(-4px);border-color:rgba(108,99,255,.35)}
    .mini-ic{width:42px;height:42px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:16px;color:#fff;flex-shrink:0}
    .mini-ic.total{background:var(--g)}
    .mini-ic.active{background:linear-gradient(135deg,#0f5132,#43e97b)}
    .mini-ic.expiring{background:linear-gradient(135deg,#7c4a03,#f5b93b)}
    .mini-ic.expired{background:linear-gradient(135deg,#7f1d3a,#ff6584)}
    .mini-val{font-size:1.15rem;font-weight:800;color:#fff;line-height:1.2}
    .mini-label{font-size:.72rem;color:rgba(255,255,255,.45);font-weight:500}

    .dashboard-card{
        background:rgba(255,255,255,.04);backdrop-filter:blur(20px);
        border:1px solid rgba(255,255,255,.08);border-radius:20px;overflow:hidden;
    }
    .card-header{
        padding:18px 22px;border-bottom:1px solid rgba(255,255,255,.07);
        display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;
    }
    .card-header h3{font-size:1.05rem;font-weight:700;margin:0;color:#fff}
    .card-body{padding:10px 22px 22px}

    .search-box{position:relative;margin-bottom:14px;max-width:320px}
    .search-box i{position:absolute;left:12px;top:50%;transform:translateY(-50%);color:rgba(255,255,255,.3);font-size:13px}
    .search-box input{
        width:100%;background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);border-radius:10px;
        padding:9px 12px 9px 34px;color:#fff;font-size:13px;outline:none;transition:.2s;
    }
    .search-box input:focus{border-color:var(--p);background:rgba(108,99,255,.08)}
    .search-box input::placeholder{color:rgba(255,255,255,.25)}

    .merchant-cell{display:flex;align-items:center;gap:10px}
    .m-avatar{
        width:34px;height:34px;border-radius:10px;background:var(--g);display:flex;align-items:center;
        justify-content:center;font-weight:800;font-size:13px;color:#fff;flex-shrink:0;
    }
    .m-name{font-weight:700;color:#fff;font-size:.87rem}
    .m-company{font-size:.72rem;color:rgba(255,255,255,.4)}

    .role-pill{
        display:inline-flex;align-items:center;gap:5px;padding:4px 10px;border-radius:20px;
        font-size:.7rem;font-weight:700;background:rgba(108,99,255,.15);color:#a99bff;
    }

    .mono{font-family:'JetBrains Mono',monospace;font-size:.78rem;color:rgba(255,255,255,.65)}
    .mask-toggle{
        background:none;border:none;color:rgba(255,255,255,.25);cursor:pointer;font-size:11px;margin-left:6px;
    }
    .mask-toggle:hover{color:var(--p)}

    .exp-pill{display:inline-flex;align-items:center;gap:5px;padding:5px 11px;border-radius:20px;font-size:.72rem;font-weight:700}
    .exp-active{background:rgba(67,233,123,.13);color:var(--success)}
    .exp-soon{background:rgba(245,185,59,.15);color:var(--warning)}
    .exp-expired{background:rgba(255,101,132,.13);color:var(--danger)}

    .act-btn{
        border:none;border-radius:9px;padding:7px 13px;font-size:.75rem;font-weight:700;cursor:pointer;
        display:inline-flex;align-items:center;gap:6px;transition:.2s;
    }
    .act-edit{background:rgba(62,166,255,.15);color:var(--info)}
    .act-edit:hover{background:rgba(62,166,255,.28)}
    .act-del{background:rgba(255,101,132,.13);color:var(--danger)}
    .act-del:hover{background:rgba(255,101,132,.28)}

    table.dataTable{color:#fff !important;border-collapse:separate !important;border-spacing:0}
    table.dataTable thead th{
        color:rgba(255,255,255,.45) !important;font-size:.72rem;text-transform:uppercase;letter-spacing:.5px;
        border-bottom:1px solid rgba(255,255,255,.08) !important;padding:12px 14px !important;font-weight:700;white-space:nowrap;
    }
    table.dataTable tbody td{
        border-bottom:1px solid rgba(255,255,255,.05) !important;padding:12px 14px !important;
        font-size:.85rem;color:rgba(255,255,255,.85);vertical-align:middle;
    }
    table.dataTable tbody tr{transition:.15s;animation:rowIn .35s ease both}
    @keyframes rowIn{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}
    table.dataTable tbody tr:hover{background:rgba(108,99,255,.06) !important}
    table.dataTable tbody tr.odd, table.dataTable tbody tr.even{background:transparent !important}
    .dataTables_wrapper .dataTables_filter, .dataTables_wrapper .dataTables_length{display:none}
    .dataTables_wrapper .dataTables_info{color:rgba(255,255,255,.4) !important;font-size:.78rem;padding-top:14px !important}
    .dataTables_wrapper .dataTables_paginate .paginate_button{
        color:rgba(255,255,255,.6) !important;border-radius:8px !important;border:1px solid transparent !important;
        padding:5px 11px !important;margin-left:4px !important;
    }
    .dataTables_wrapper .dataTables_paginate .paginate_button.current{background:var(--g) !important;color:#fff !important;border:none !important}
    .dataTables_wrapper .dataTables_paginate .paginate_button:hover{background:rgba(255,255,255,.08) !important;color:#fff !important}
    .dataTables_wrapper .dataTables_paginate .paginate_button.disabled{opacity:.3}

    .empty-state{text-align:center;padding:60px 20px;color:rgba(255,255,255,.35)}
    .empty-state i{font-size:2.4rem;margin-bottom:14px;display:block;color:rgba(255,255,255,.15)}
    .empty-state h4{color:rgba(255,255,255,.55);font-size:1rem;margin-bottom:6px}

    .mobile-cards{display:none}
    @media(max-width:900px){
        .mini-stats{grid-template-columns:repeat(2,1fr)}
        .card-body{padding:10px 12px 18px}
        .mw-head p{margin-left:0}
        .table-responsive{display:none}
        .mobile-cards{display:block}
        .m-card{
            background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.07);border-radius:14px;
            padding:14px;margin-bottom:10px;animation:rowIn .3s ease both;
        }
        .m-card-top{display:flex;justify-content:space-between;align-items:center;margin-bottom:10px}
        .m-card-row{display:flex;justify-content:space-between;font-size:.78rem;padding:5px 0;color:rgba(255,255,255,.55)}
        .m-card-row span:last-child{color:#fff;font-weight:600;text-align:right}
        .m-card-actions{display:flex;gap:8px;margin-top:10px}
        .m-card-actions form{flex:1}
        .m-card-actions .act-btn{width:100%;justify-content:center}
    }
</style>

<div class="mw-wrap">
    <div class="mw-head">
        <div>
            <h1><span class="icn"><i class="fas fa-store"></i></span>Merchant List</h1>
            <p>All registered merchants on your gateway</p>
        </div>
        <a href="add_merchant" class="btn-primary-cta"><i class="fas fa-plus"></i> Add Merchant</a>
    </div>

    <div class="mini-stats">
        <div class="mini-card">
            <div class="mini-ic total"><i class="fas fa-users"></i></div>
            <div><div class="mini-val"><?php echo number_format($totalMerchants); ?></div><div class="mini-label">Total Merchants</div></div>
        </div>
        <div class="mini-card">
            <div class="mini-ic active"><i class="fas fa-circle-check"></i></div>
            <div><div class="mini-val"><?php echo number_format($activeCount); ?></div><div class="mini-label">Active</div></div>
        </div>
        <div class="mini-card">
            <div class="mini-ic expiring"><i class="fas fa-clock"></i></div>
            <div><div class="mini-val"><?php echo number_format($expiringCount); ?></div><div class="mini-label">Expiring ≤ 7 days</div></div>
        </div>
        <div class="mini-card">
            <div class="mini-ic expired"><i class="fas fa-triangle-exclamation"></i></div>
            <div><div class="mini-val"><?php echo number_format($expiredCount); ?></div><div class="mini-label">Expired</div></div>
        </div>
    </div>

    <div class="dashboard-card">
        <div class="card-header"><h3>All Merchants</h3></div>
        <div class="card-body">
            <div class="search-box">
                <i class="fas fa-search"></i>
                <input type="text" id="mSearch" placeholder="Search name, mobile, company...">
            </div>

            <?php if ($totalMerchants === 0): ?>
                <div class="empty-state">
                    <i class="fas fa-store-slash"></i>
                    <h4>No merchants yet</h4>
                    <p>Merchants you onboard will show up here.</p>
                </div>
            <?php else: ?>
            <div class="table-responsive">
                <table class="table" id="example-table" style="width:100%">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Merchant</th>
                            <th>Type</th>
                            <th>Mobile No</th>
                            <th>PAN No</th>
                            <th>Aadhaar No</th>
                            <th>Address</th>
                            <th>Expiry</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($merchants as $row):
                        $exp = $row['expiry'] ?? null;
                        $expClass = 'exp-active'; $expIcon = 'fa-circle-check'; $expText = $exp ? $exp : 'No expiry';
                        if ($exp) {
                            $days = (strtotime($exp) - strtotime($today)) / 86400;
                            if ($days < 0) { $expClass = 'exp-expired'; $expIcon = 'fa-triangle-exclamation'; }
                            elseif ($days <= 7) { $expClass = 'exp-soon'; $expIcon = 'fa-clock'; }
                        }
                        $nameSafe = htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8');
                        $initials = strtoupper(substr($nameSafe, 0, 1) . (strpos($nameSafe, ' ') ? substr(strrchr($nameSafe, ' '), 1, 1) : ''));
                        $panSafe = htmlspecialchars($row['pan'], ENT_QUOTES, 'UTF-8');
                        $aadhaarSafe = htmlspecialchars($row['aadhaar'], ENT_QUOTES, 'UTF-8');
                    ?>
                        <tr>
                            <td class="mono">#<?php echo htmlspecialchars($row['id']); ?></td>
                            <td>
                                <div class="merchant-cell">
                                    <div class="m-avatar"><?php echo $initials ?: '?'; ?></div>
                                    <div>
                                        <div class="m-name"><?php echo $nameSafe; ?></div>
                                        <div class="m-company"><?php echo htmlspecialchars($row['company'], ENT_QUOTES, 'UTF-8'); ?></div>
                                    </div>
                                </div>
                            </td>
                            <td><span class="role-pill"><i class="fas fa-user-tag"></i> <?php echo htmlspecialchars($row['role'], ENT_QUOTES, 'UTF-8'); ?></span></td>
                            <td class="mono"><?php echo htmlspecialchars($row['mobile'], ENT_QUOTES, 'UTF-8'); ?></td>
                            <td>
                                <span class="mono sensitive-val" data-full="<?php echo $panSafe; ?>" data-masked="<?php echo maskMiddle($panSafe); ?>"><?php echo maskMiddle($panSafe); ?></span>
                                <button class="mask-toggle" onclick="toggleMask(this)"><i class="fas fa-eye"></i></button>
                            </td>
                            <td>
                                <span class="mono sensitive-val" data-full="<?php echo $aadhaarSafe; ?>" data-masked="<?php echo maskMiddle($aadhaarSafe); ?>"><?php echo maskMiddle($aadhaarSafe); ?></span>
                                <button class="mask-toggle" onclick="toggleMask(this)"><i class="fas fa-eye"></i></button>
                            </td>
                            <td><?php echo htmlspecialchars($row['location'], ENT_QUOTES, 'UTF-8'); ?></td>
                            <td><span class="exp-pill <?php echo $expClass; ?>"><i class="fas <?php echo $expIcon; ?>"></i> <?php echo htmlspecialchars($expText); ?></span></td>
                            <td>
                                <div style="display:flex;gap:8px">
                                    <form action="edituser.php" method="post">
                                        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                                        <input type="hidden" name="mobileno" value="<?php echo htmlspecialchars($row['mobile']); ?>">
                                        <button class="act-btn act-edit" name="edituser"><i class="fas fa-pen"></i> Edit</button>
                                    </form>
                                    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST" onsubmit="return confirmDelete(event, this);">
                                        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                                        <input type="hidden" name="mobileno" value="<?php echo htmlspecialchars($row['mobile']); ?>">
                                        <button class="act-btn act-del" name="delete"><i class="fas fa-trash"></i> Delete</button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <!-- Mobile stacked card view -->
            <div class="mobile-cards">
                <?php foreach ($merchants as $row):
                    $exp = $row['expiry'] ?? null;
                    $expClass = 'exp-active'; $expIcon = 'fa-circle-check'; $expText = $exp ? $exp : 'No expiry';
                    if ($exp) {
                        $days = (strtotime($exp) - strtotime($today)) / 86400;
                        if ($days < 0) { $expClass = 'exp-expired'; $expIcon = 'fa-triangle-exclamation'; }
                        elseif ($days <= 7) { $expClass = 'exp-soon'; $expIcon = 'fa-clock'; }
                    }
                ?>
                <div class="m-card">
                    <div class="m-card-top">
                        <div class="merchant-cell">
                            <div class="m-avatar"><?php echo strtoupper(substr(htmlspecialchars($row['name']),0,1)); ?></div>
                            <div>
                                <div class="m-name"><?php echo htmlspecialchars($row['name']); ?></div>
                                <div class="m-company"><?php echo htmlspecialchars($row['company']); ?></div>
                            </div>
                        </div>
                        <span class="exp-pill <?php echo $expClass; ?>"><i class="fas <?php echo $expIcon; ?>"></i></span>
                    </div>
                    <div class="m-card-row"><span>Mobile</span><span><?php echo htmlspecialchars($row['mobile']); ?></span></div>
                    <div class="m-card-row"><span>PAN</span><span><?php echo maskMiddle(htmlspecialchars($row['pan'])); ?></span></div>
                    <div class="m-card-row"><span>Aadhaar</span><span><?php echo maskMiddle(htmlspecialchars($row['aadhaar'])); ?></span></div>
                    <div class="m-card-row"><span>Expiry</span><span><?php echo htmlspecialchars($expText); ?></span></div>
                    <div class="m-card-actions">
                        <form action="edituser.php" method="post">
                            <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                            <input type="hidden" name="mobileno" value="<?php echo htmlspecialchars($row['mobile']); ?>">
                            <button class="act-btn act-edit" name="edituser"><i class="fas fa-pen"></i> Edit</button>
                        </form>
                        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST" onsubmit="return confirmDelete(event, this);">
                            <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                            <input type="hidden" name="mobileno" value="<?php echo htmlspecialchars($row['mobile']); ?>">
                            <button class="act-btn act-del" name="delete"><i class="fas fa-trash"></i> Delete</button>
                        </form>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>
<script src="./assets/vendors/jquery/dist/jquery.min.js" type="text/javascript"></script>
<script src="./assets/vendors/popper.js/dist/umd/popper.min.js" type="text/javascript"></script>
<script src="./assets/vendors/bootstrap/dist/js/bootstrap.min.js" type="text/javascript"></script>
<script src="./assets/vendors/metisMenu/dist/metisMenu.min.js" type="text/javascript"></script>
<script src="./assets/vendors/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script>
<script src="./assets/vendors/DataTables/datatables.min.js" type="text/javascript"></script>
<script src="./assets/js/scripts/dashboard_1_demo.js" type="text/javascript"></script>
<script src="assets/js/app.min.js" type="text/javascript"></script>
<script>
    var table = $('#example-table').DataTable({ pageLength: 10 });
    $('#mSearch').on('keyup', function() {
        table.search(this.value).draw();
        var term = this.value.toLowerCase();
        $('.mobile-cards .m-card').each(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf(term) !== -1);
        });
    });

    // reveal/hide masked PAN & Aadhaar values in place
    function toggleMask(btn) {
        var span = btn.previousElementSibling;
        var icon = btn.querySelector('i');
        if (span.textContent === span.dataset.masked) {
            span.textContent = span.dataset.full;
            icon.className = 'fas fa-eye-slash';
        } else {
            span.textContent = span.dataset.masked;
            icon.className = 'fas fa-eye';
        }
    }

    // swap the native browser confirm() for a themed SweetAlert2 confirmation
    // before actually submitting the delete form
    function confirmDelete(e, form) {
        e.preventDefault();
        Swal.fire({
            title: 'Delete this merchant?',
            text: 'This action cannot be undone.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, delete',
            cancelButtonText: 'Cancel',
            confirmButtonColor: '#ff6584',
            cancelButtonColor: '#3a3a4a',
            background: '#14141f',
            color: '#fff'
        }).then((result) => {
            if (result.isConfirmed) form.submit();
        });
        return false;
    }
</script>
</body>
</html>
