<?php include "header.php"; ?>
<?php
include_once __DIR__ . '/../includes/subscription_lib.php';
include_once __DIR__ . '/../includes/merchant_lib.php';
?>
<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">

<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}

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

    .cm-head{margin-bottom:22px}
    .cm-head h1{font-size:1.55rem;font-weight:800;margin:0;color:#fff;display:flex;align-items:center;gap:10px}
    .cm-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);
    }
    .cm-head p{font-size:.85rem;color:rgba(255,255,255,.45);margin:4px 0 0 48px}

    .glass-card{
        background:rgba(255,255,255,.04);backdrop-filter:blur(20px);
        border:1px solid rgba(255,255,255,.08);border-radius:20px;overflow:hidden;margin-bottom:20px;
    }
    .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;display:flex;align-items:center;gap:8px}
    .card-header h3 i{color:var(--p)}
    .card-body{padding:22px}

    .form-grid{display:grid;grid-template-columns:1fr 1fr auto;gap:16px;align-items:end}
    @media(max-width:768px){.form-grid{grid-template-columns:1fr}}
    .form-label{display:block;font-size:.78rem;font-weight:600;color:rgba(255,255,255,.5);margin-bottom:7px;text-transform:uppercase;letter-spacing:.3px}
    .form-control{
        width:100%;background:rgba(255,255,255,.05);border:1.5px solid rgba(255,255,255,.1);border-radius:10px;
        padding:11px 13px;color:#fff;font-size:.88rem;outline:none;transition:.2s;font-family:'Inter',sans-serif;
    }
    .form-control:focus{border-color:var(--p);background:rgba(108,99,255,.08);box-shadow:0 0 0 3px rgba(108,99,255,.15)}
    .form-control::placeholder{color:rgba(255,255,255,.3)}
    select.form-control{
        color:#fff !important;-webkit-appearance:none;-moz-appearance:none;appearance:none;
        background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='14' height='9' viewBox='0 0 14 9'><path d='M1 1l6 6 6-6' stroke='%23a99bff' stroke-width='2' fill='none' stroke-linecap='round' stroke-linejoin='round'/></svg>");
        background-repeat:no-repeat;background-position:right 14px center;padding-right:36px;
    }
    select.form-control option{background:#14141f;color:#fff}

    .btn-primary-cta{
        background:var(--g);border:none;color:#fff;padding:11px 22px;border-radius:10px;
        font-size:.85rem;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;gap:8px;
        transition:.2s;box-shadow:0 6px 18px rgba(108,99,255,.3);width:100%;white-space:nowrap;
    }
    .btn-primary-cta:hover{transform:translateY(-1px);box-shadow:0 10px 24px rgba(108,99,255,.45);color:#fff}

    .gw-badge{display:inline-flex;align-items:center;gap:7px;font-weight:700;font-size:.82rem;color:#fff}
    .gw-dot{width:8px;height:8px;border-radius:50%;flex-shrink:0}
    .gw-hdfc{color:#1e40af}.gw-sbi{color:#0891b2}.gw-phonepe{color:#6d28d9}.gw-paytm{color:#0ea5e9}
    .gw-bharatpe{color:#ea580c}.gw-mobikwik{color:#f59e0b}.gw-freecharge{color:#dc2626}.gw-fampay{color:#e040fb}

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

    .mono{font-family:'JetBrains Mono',monospace;font-size:.8rem;color:rgba(255,255,255,.65)}
    .date-chip{
        background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);color:rgba(255,255,255,.7);
        padding:5px 11px;border-radius:8px;font-size:.75rem;font-weight:600;
    }
    .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-verify{background:rgba(62,166,255,.15);color:var(--info)}
    .act-verify: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.table{width:100%;color:#fff;border-collapse:separate;border-spacing:0}
    table.table thead th{
        color:rgba(255,255,255,.45);font-size:.72rem;text-transform:uppercase;letter-spacing:.5px;
        border-bottom:1px solid rgba(255,255,255,.08);padding:12px 14px;font-weight:700;white-space:nowrap;text-align:left;
    }
    table.table tbody td{
        border-bottom:1px solid rgba(255,255,255,.05);padding:12px 14px;
        font-size:.85rem;color:rgba(255,255,255,.85);vertical-align:middle;
    }
    table.table tbody tr{transition:.15s;animation:rowIn .35s ease both}
    @keyframes rowIn{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}
    table.table tbody tr:hover{background:rgba(108,99,255,.06)}

    .empty-state{text-align:center;padding:50px 20px;color:rgba(255,255,255,.35)}
    .empty-state i{font-size:2.2rem;margin-bottom:12px;display:block;color:rgba(255,255,255,.15)}
    .empty-state h4{color:rgba(255,255,255,.55);font-size:.95rem;margin-bottom:4px}

    .mobile-cards{display:none}
    @media(max-width:900px){
        .card-body{padding:14px}
        .table-responsive{display:none}
        .mobile-cards{display:block}
        .mc-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;
        }
        .mc-top{display:flex;justify-content:space-between;align-items:center;margin-bottom:8px}
        .mc-row{display:flex;justify-content:space-between;font-size:.78rem;padding:5px 0;color:rgba(255,255,255,.55)}
        .mc-row span:last-child{color:#fff;font-weight:600;text-align:right}
        .mc-actions{display:flex;gap:8px;margin-top:10px}
        .mc-actions form{flex:1}
        .mc-actions .act-btn{width:100%;justify-content:center}
    }

    /* ---- FamPay "Verification Method" chooser modal ---- */
    .swal-glass-popup{
        background:rgba(24,22,38,.75) !important;backdrop-filter:blur(28px) saturate(180%);
        border:1px solid rgba(255,255,255,.14) !important;border-radius:22px !important;
        box-shadow:0 24px 70px rgba(0,0,0,.55) !important;color:#fff !important;
    }
    .swal-glass-popup .swal2-title{color:#fff !important;font-weight:800}
    .swal-glass-popup .swal2-html-container{color:rgba(255,255,255,.6) !important}
    .swal-glass-popup input.swal2-input, .swal-glass-popup input.vm-input{
        background:rgba(255,255,255,.06) !important;border:1px solid rgba(255,255,255,.14) !important;
        color:#fff !important;border-radius:10px !important;
    }
    .swal-glass-confirm, .swal-glass-cancel{
        padding:10px 22px;border-radius:10px;font-size:.85rem;font-weight:700;cursor:pointer;border:none;
    }
    .swal-glass-confirm{background:var(--g) !important;color:#fff !important;box-shadow:0 6px 18px rgba(108,99,255,.35)}
    .swal-glass-cancel{background:rgba(255,255,255,.07) !important;color:#fff !important;border:1px solid rgba(255,255,255,.14) !important}

    .vm-option{
        position:relative;text-align:left;border:1.5px solid rgba(255,255,255,.12);border-radius:14px;
        padding:14px 16px;margin-bottom:12px;cursor:pointer;transition:.15s;background:rgba(255,255,255,.03);
    }
    .vm-option:hover{background:rgba(255,255,255,.06)}
    .vm-option.selected{border-color:var(--p);background:rgba(108,99,255,.1);box-shadow:0 0 0 1px var(--p)}
    .vm-option .vm-badge{
        position:absolute;top:-9px;right:14px;background:var(--success);color:#062;font-size:.63rem;
        font-weight:800;padding:2px 9px;border-radius:20px;letter-spacing:.3px;
    }
    .vm-option-title{font-weight:700;font-size:.92rem;color:#fff;margin-bottom:2px}
    .vm-option-sub{font-size:.76rem;color:rgba(255,255,255,.45)}
    .vm-input-label{display:block;font-size:.72rem;font-weight:700;color:rgba(255,255,255,.45);margin:12px 0 5px;text-align:left;text-transform:uppercase;letter-spacing:.3px}
    .vm-input{width:100%;padding:10px 12px;font-size:.85rem}
</style>

<div class="cm-wrap">
    <div class="cm-head">
        <h1><span class="icn"><i class="fas fa-link"></i></span>Merchant Connect Settings</h1>
        <p>Connect and manage UPI/payment gateways linked to your account</p>
    </div>

    <div class="glass-card">
        <div class="card-header"><h3><i class="fas fa-plus-circle"></i> Connect New Gateway</h3></div>
        <div class="card-body">
<?php

// ini_set('display_errors', 1);
// error_reporting(E_ALL);

if(isset($_POST['addmerchant'])){

    // Enforce the cashier/merchant limit from the user's active plan
    $cashierLimit = getCashierLimit($conn, $userdata['id']);
    $freshUserRow = $conn->query("SELECT * FROM users WHERE id = " . (int)$userdata['id'])->fetch_assoc();
    $connectedNow = buildConnectedMapFromUserRow($freshUserRow);
    $connectedCount = count(array_filter($connectedNow, function($v){ return $v === 'Yes'; }));

    if ($connectedCount >= $cashierLimit) {
        $limitMsg = ($cashierLimit <= 0)
            ? 'Please purchase a subscription plan before connecting a merchant.'
            : 'Your plan allows only ' . $cashierLimit . ' merchant(s). Disconnect one first or upgrade your plan.';
        echo '<script src="js/jquery-3.2.1.min.js"></script><script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script><script>
            Swal.fire({
                icon: "error",
                title: "Merchant Limit Reached",
                text: "'.$limitMsg.'",
                confirmButtonText: "Ok"
            }).then(() => { window.location.href = "connect_merchant"; });
        </script>';
        exit;
    }

    $bbbytemerchant = mysqli_real_escape_string($conn, $_POST['merchant_name']);
    
    if ($bbbytemerchant=="hdfc"){
    $no = mysqli_real_escape_string($conn, $_POST['c_mobile']);
    $data = "INSERT INTO hdfc(id, number, seassion, device_id, user_token, pin, upi_hdfc, UPI, tidlist, status, mobile) VALUES ('','$no','','','" . $userdata['user_token'] . "','','','','', 'Deactive','$mobile')";
    $insert = mysqli_query($conn, $data);
    }
    
    elseif ($bbbytemerchant=="phonepe"){
        $no = mysqli_real_escape_string($conn, $_POST['c_mobile']);
        $bbbytetokken=$userdata['user_token'];
        
        $data = "INSERT INTO phonepe_tokens (user_token, phoneNumber, userId, token, refreshToken, name, device_data)
        VALUES ('$bbbytetokken', '$no', '', '', '', '', '')";
$insert = mysqli_query($conn, $data);


    }
    elseif ($bbbytemerchant=="paytm"){
        $no = mysqli_real_escape_string($conn, $_POST['c_mobile']);
        $bbbytetokken=$userdata['user_token'];
        
        $data = "INSERT INTO paytm_tokens (user_token, phoneNumber, MID, Upiid)
        VALUES ('$bbbytetokken', '$no', '','')";
        $insert = mysqli_query($conn, $data);


    }
    
    elseif ($bbbytemerchant=="bharatpe"){
        $no = mysqli_real_escape_string($conn, $_POST['c_mobile']);
        $bbbytetokken=$userdata['user_token'];
        
        $data = "INSERT INTO bharatpe_tokens (user_token, phoneNumber, token, cookie, merchantId)
        VALUES ('$bbbytetokken', '$no', '', '', '')";
$insert = mysqli_query($conn, $data);
     }
     
     elseif ($bbbytemerchant=="googlepay"){
        $no = mysqli_real_escape_string($conn, $_POST['c_mobile']);
        $bbbytetokken=$userdata['user_token'];
        
        $data = "INSERT INTO googlepay_tokens (user_token, phoneNumber, Instance_Id, Upiid)
        VALUES ('$bbbytetokken', '$no', '','')";
        $insert = mysqli_query($conn, $data);


    }

    elseif ($bbbytemerchant=="sbi"){
        $no = mysqli_real_escape_string($conn, $_POST['c_mobile']);
        $bbbytetokken=$userdata['user_token'];
        
         $fcuser_id = $_SESSION['user_id']; // Assuming the user ID is stored in the session

$data = "INSERT INTO sbi_token (user_token, phoneNumber, user_id)
         VALUES ('$bbbytetokken', '$no', '$fcuser_id')";
$insert = mysqli_query($conn, $data);



    }
    
    
     elseif ($bbbytemerchant=="freecharge"){
        $no = mysqli_real_escape_string($conn, $_POST['c_mobile']);
        $bbbytetokken=$userdata['user_token'];
        
         $fcuser_id = $_SESSION['user_id']; // Assuming the user ID is stored in the session

$data = "INSERT INTO freecharge_token (user_token, phoneNumber, user_id)
         VALUES ('$bbbytetokken', '$no', '$fcuser_id')";
$insert = mysqli_query($conn, $data);



    }
    elseif ($bbbytemerchant=="mobikwik"){
        $no = mysqli_real_escape_string($conn, $_POST['c_mobile']);
        $bbbytetokken=$userdata['user_token'];
        
         $fcuser_id = $_SESSION['user_id']; // Assuming the user ID is stored in the session

$data = "INSERT INTO mobikwik_token (user_token, phoneNumber, user_id)
         VALUES ('$bbbytetokken', '$no', '$fcuser_id')";
$insert = mysqli_query($conn, $data);



    }
    
    elseif ($bbbytemerchant=="fampay"){
        $no = mysqli_real_escape_string($conn, $_POST['c_mobile']);
        $bbbytetokken=$userdata['user_token'];
        $upiId = mysqli_real_escape_string($conn, trim($_POST['upi_id'] ?? ''));

        if ($upiId === '') {
            echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script><script>
                Swal.fire({
                    icon: "error",
                    title: "UPI ID Required",
                    text: "FamPay connect karne ke liye UPI ID / VPA daalna zaroori hai (QR code isi se banega).",
                    confirmButtonText: "Ok"
                }).then(() => { window.location.href = "connect_merchant"; });
            </script>';
            exit;
        }

        $data = "INSERT INTO fampay_tokens (user_token, phoneNumber, upi_id, gmail, app_password, status)
        VALUES ('$bbbytetokken', '$no', '$upiId', '', '', 'Deactive')";
        $insert = mysqli_query($conn, $data);

    }
    
        
    
    
    if($insert){
        
        
        
        
        // Show SweetAlert2 success message
                            
 echo '<script src="js/jquery-3.2.1.min.js"></script>';
 echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';         echo '<script>         $("#loading_ajax").hide();
    Swal.fire({
        icon: "success",
        title: "Congratulations! Your Merchant Hasbeen Added Successfully!",
        showConfirmButton: true, // Show the confirm button
        confirmButtonText: "Ok!", // Set text for the confirm button
        allowOutsideClick: false, // Prevent the user from closing the popup by clicking outside
        allowEscapeKey: false // Prevent the user from closing the popup by pressing Escape key
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = "connect_merchant"; // Redirect to "connect_merchant" when the user clicks the confirm button
        }
    });
</script>';
 exit;
        
    
        
        
    }else{
        
        
        // Show SweetAlert2 error message
                            
 echo '<script src="js/jquery-3.2.1.min.js"></script>';         echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';         echo '<script>         $("#loading_ajax").hide();
    Swal.fire({
        icon: "error",
        title: "Opps Sorry Merhcant Adding Failure!",
        showConfirmButton: true, // Show the confirm button
        confirmButtonText: "Ok!", // Set text for the confirm button
        allowOutsideClick: false, // Prevent the user from closing the popup by clicking outside
        allowEscapeKey: false // Prevent the user from closing the popup by pressing Escape key
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = "dashboard"; // Redirect to "dashboard" when the user clicks the confirm button
        }
    });
</script>';
exit;

    }
}


if (isset($_POST['delete'])) {
    
    
    

 

    $merchant_type = mysqli_real_escape_string($conn, $_POST['merchant_type']);
    $token = $userdata['user_token'];

    // Initialize the delete and update queries
    $del = "";
    $update = "";

    // Construct the delete and update queries based on merchant type
    if ($merchant_type == 'hdfc') {
        $del = "DELETE FROM hdfc WHERE user_token = '$token'";
        $update = "UPDATE users SET hdfc_connected = 'No' WHERE user_token = '$token'";
    } elseif ($merchant_type == 'phonepe') {
        $del = "DELETE FROM phonepe_tokens WHERE user_token = '$token'";
        $update = "UPDATE users SET phonepe_connected = 'No' WHERE user_token = '$token'";
        
        // Add a query to delete from the store_id table as well
        $del_store_id = "DELETE FROM store_id WHERE user_token = '$token'";
        mysqli_query($conn, $del_store_id);
    } elseif ($merchant_type == 'paytm') {
        $del = "DELETE FROM paytm_tokens WHERE user_token = '$token'";
        $update = "UPDATE users SET paytm_connected = 'No' WHERE user_token = '$token'";
    } elseif ($merchant_type == 'bharatpe') {
        $del = "DELETE FROM bharatpe_tokens WHERE user_token = '$token'";
        $update = "UPDATE users SET bharatpe_connected = 'No' WHERE user_token = '$token'";
    }  elseif ($merchant_type == 'googlepay') {
        
        $del = "DELETE FROM googlepay_tokens WHERE user_token = '$token'";
        $update = "UPDATE users SET googlepay_connected = 'No' WHERE user_token = '$token'";
        
    } elseif ($merchant_type == 'freecharge') {
        
        $del = "DELETE FROM freecharge_token WHERE user_token = '$token'";
        $update = "UPDATE users SET freecharge_connected = 'No' WHERE user_token = '$token'";
        
    }
    elseif ($merchant_type == 'sbi') {
        
        $del = "DELETE FROM sbi_token WHERE user_token = '$token'";
        $update = "UPDATE users SET sbi_connected = 'No' WHERE user_token = '$token'";
        
    }  
    elseif ($merchant_type == 'mobikwik') {
        
        $del = "DELETE FROM mobikwik_token WHERE user_token = '$token'";
        $update = "UPDATE users SET mobikwik_connected = 'No' WHERE user_token = '$token'";
        
    }
    elseif ($merchant_type == 'fampay') {
        
        $del = "DELETE FROM fampay_tokens WHERE user_token = '$token'";
        $update = "UPDATE users SET fampay_connected = 'No' WHERE user_token = '$token'";
        
    }

    // Execute the delete query
    $res_del = mysqli_query($conn, $del);

    // Execute the update query
    $res_update = mysqli_query($conn, $update);

    if ($res_del && $res_update) {
        // Show SweetAlert2 success message
        
         echo '<script src="js/jquery-3.2.1.min.js"></script>';         echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';         echo '<script>         $("#loading_ajax").hide();
    Swal.fire({
        icon: "success",
        title: "Congratulations! Your Merchant Has been Deleted Successfully!",
        showConfirmButton: true,
        confirmButtonText: "Ok!",
        allowOutsideClick: false,
        allowEscapeKey: false
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = "connect_merchant";
        }
    });
</script>';
        exit;
    } else {
        // Show SweetAlert2 error message
        
         echo '<script src="js/jquery-3.2.1.min.js"></script>';         echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';         echo '<script>         $("#loading_ajax").hide();
    Swal.fire({
        icon: "error",
        title: "Merchant Not Deleted! Contact Admin",
        showConfirmButton: true,
        confirmButtonText: "Ok!",
        allowOutsideClick: false,
        allowEscapeKey: false
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = "connect_merchant";
        }
    });
</script>';
        exit;
    }
}

if (isset($_POST['savePaymentMode'])) {
    $chosen = $_POST['payment_merchant_choice'] ?? 'random';
    $token  = mysqli_real_escape_string($conn, $userdata['user_token']);

    if ($chosen === 'random') {
        $modeEsc = 'random';
        mysqli_query($conn, "UPDATE users SET merchant_mode = '$modeEsc', active_merchant_type = NULL WHERE user_token = '$token'");
    } else {
        $modeEsc = 'specific';
        $typeEsc = mysqli_real_escape_string($conn, $chosen);
        mysqli_query($conn, "UPDATE users SET merchant_mode = '$modeEsc', active_merchant_type = '$typeEsc' WHERE user_token = '$token'");
    }

    echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script><script>
        Swal.fire({
            icon: "success",
            title: "Payment Merchant Preference Saved!",
            showConfirmButton: true,
            confirmButtonText: "Ok!",
            allowOutsideClick: false,
            allowEscapeKey: false
        }).then(() => { window.location.href = "connect_merchant"; });
    </script>';
    exit;
}

?>





						<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" id="merchant">
    <div class="form-grid">
        <div>
            <label class="form-label">Merchant Gateway</label>
            <select name="merchant_name" id="merchantGatewaySelect" class="form-control">
                <option value="paytm">Paytm</option>
                <option value="fampay">FamPay</option>
            </select>
        </div>
        <div id="upiIdField" style="display:none">
            <label class="form-label">UPI ID / VPA</label>
            <input type="text" name="upi_id" id="upiIdInput" placeholder="e.g. name@fam or 9876543210@fam" class="form-control">
            <small style="color:rgba(255,255,255,.4);font-size:.72rem">Yahi UPI ID QR code / payment link banane ke liye use hoga.</small>
        </div>
        <div>
            <label class="form-label">Cashier Mobile Number</label>
            <input type="number" name="c_mobile" placeholder="Enter 10-digit mobile number" class="form-control" onkeypress="if(this.value.length==10) return false;" required="">
        </div>
        <div>
            <button type="submit" name="addmerchant" class="btn-primary-cta"><i class="fas fa-plug"></i> Connect</button>
        </div>
    </div>
</form>
<script>
    (function(){
        var gatewaysNeedingUpi = ['fampay'];
        var sel = document.getElementById('merchantGatewaySelect');
        var wrap = document.getElementById('upiIdField');
        var input = document.getElementById('upiIdInput');
        function toggle(){
            var needsUpi = gatewaysNeedingUpi.indexOf(sel.value) !== -1;
            wrap.style.display = needsUpi ? '' : 'none';
            input.required = needsUpi;
        }
        sel.addEventListener('change', toggle);
        toggle();
    })();
</script>
        </div>
    </div>

    <div class="glass-card">
        <div class="card-header"><h3><i class="fas fa-store"></i> All Connected Merchants</h3></div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table" id="dataTable" width="100%">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Gateway</th>
                                    <th>Mobile Number</th>
                                    <th>Last Sync</th>
                                    <th>Status</th>
                                    <th>Verify</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
$cxrrrrtoken = $userdata['user_token'];
$fetchData = "
    SELECT 'hdfc' AS merchant_type, id, number, date, status FROM hdfc WHERE user_token = '$cxrrrrtoken' 
    UNION ALL 
    SELECT 'phonepe' AS merchant_type, sl AS id, phoneNumber AS number, date, status FROM phonepe_tokens WHERE user_token = '$cxrrrrtoken'
    UNION ALL
    SELECT 'paytm' AS merchant_type, id, phoneNumber AS number, date, status FROM paytm_tokens WHERE user_token = '$cxrrrrtoken'
    UNION ALL
    SELECT 'bharatpe' AS merchant_type, id, phoneNumber AS number, date, status FROM bharatpe_tokens WHERE user_token = '$cxrrrrtoken'
    UNION ALL
    SELECT 'googlepay' AS merchant_type, id, phoneNumber AS number, date, status FROM googlepay_tokens WHERE user_token = '$cxrrrrtoken'
    UNION ALL
    SELECT 'freecharge' AS merchant_type, id, phoneNumber AS number, date, status FROM freecharge_token WHERE user_token = '$cxrrrrtoken'
    UNION ALL
    SELECT 'sbi' AS merchant_type, id, phoneNumber AS number, date, status FROM sbi_token WHERE user_token = '$cxrrrrtoken'
    UNION ALL
    SELECT 'mobikwik' AS merchant_type, id, phoneNumber AS number, date, status FROM mobikwik_token WHERE user_token = '$cxrrrrtoken'
    UNION ALL
    SELECT 'fampay' AS merchant_type, id, phoneNumber AS number, date, status FROM fampay_tokens WHERE user_token = '$cxrrrrtoken'
";

// echo $fetchData;

$ssData = mysqli_query($conn, $fetchData);
$connectedMerchants = [];
if ($ssData) {
    while ($row = mysqli_fetch_array($ssData)) {
        $connectedMerchants[] = $row;
    }
}
$foundAnyMerchant = count($connectedMerchants) > 0;

if ($foundAnyMerchant) {
    $counter = 1;
    foreach ($connectedMerchants as $merchant) {
        $pillClass = ($merchant['status'] == 'Active') ? 'pill-success' : 'pill-danger';
        $pillIcon = ($merchant['status'] == 'Active') ? 'fa-circle-check' : 'fa-circle-xmark';
        ?>
        <tr>
            <td class="mono">#<?php echo $counter++; ?></td>
            <td><span class="gw-badge gw-<?php echo htmlspecialchars(strtolower($merchant['merchant_type'])); ?>"><span class="gw-dot" style="background:currentColor"></span><?php echo !empty($merchant['merchant_type']) ? strtoupper(htmlspecialchars($merchant['merchant_type'], ENT_QUOTES, 'UTF-8')) : ''; ?></span></td>
            <td class="mono"><?php echo !empty($merchant['number']) ? htmlspecialchars($merchant['number'], ENT_QUOTES, 'UTF-8') : ''; ?></td>
            <td>
                <span class="date-chip"><?php echo !empty($merchant['date']) ? htmlspecialchars($merchant['date'], ENT_QUOTES, 'UTF-8') : '—'; ?></span>
            </td>
            <td>
                <span class="pill <?php echo $pillClass; ?>"><i class="fas <?php echo $pillIcon; ?>"></i> <?php echo htmlspecialchars($merchant['status'], ENT_QUOTES, 'UTF-8'); ?></span>
            </td>
            <td>
<?php
if ($merchant['merchant_type'] == 'hdfc') {
    ?>
    <form action="send_hdfcotp" method="post">
        <input type="hidden" name="hdfc_mobile" value="<?php echo $merchant['number']; ?>">
        
        <button class="act-btn act-verify" name="Verify"><i class="fas fa-shield-halved"></i> Verify</button>
    </form>
    <?php
} elseif ($merchant['merchant_type'] == 'phonepe') {
    ?>
    <form action="send_phonepeotp" method="post">
        <input type="hidden" name="phonepe_mobile" value="<?php echo $merchant['number']; ?>">
        
        <button class="act-btn act-verify" name="Verify"><i class="fas fa-shield-halved"></i> Verify</button>
    </form>
    <?php
} elseif ($merchant['merchant_type'] == 'paytm') {
    ?>
    <form action="send_paytmotp" method="post">
        <input type="hidden" name="paytm_mobile" value="<?php echo $merchant['number']; ?>">
        
        <button class="act-btn act-verify" name="Verify"><i class="fas fa-shield-halved"></i> Verify</button>
    </form>
    <?php
} elseif ($merchant['merchant_type'] == 'bharatpe') {
    ?>
    <form action="send_bharatpeotp" method="post">
        <input type="hidden" name="bharatpe_mobile" value="<?php echo $merchant['number']; ?>">
        
        <button class="act-btn act-verify" name="Verify"><i class="fas fa-shield-halved"></i> Verify</button>
    </form>
    <?php
} elseif ($merchant['merchant_type'] == 'googlepay') {
    ?>
    <form action="send_googlepayotp" method="post">
        <input type="hidden" name="googlepay_mobile" value="<?php echo $merchant['number']; ?>">
        
        <button class="act-btn act-verify" name="Verify"><i class="fas fa-shield-halved"></i> Verify</button>
    </form>
    <?php
} elseif ($merchant['merchant_type'] == 'freecharge') {
    ?>
    <form action="send_freechargeotp" method="post">
        <input type="hidden" name="freecharge_mobile" value="<?php echo $merchant['number']; ?>">
        
        <button class="act-btn act-verify" name="Verify"><i class="fas fa-shield-halved"></i> Verify</button>
    </form>
    <?php
} elseif ($merchant['merchant_type'] == 'sbi') {
    ?>
    <form action="send_sbiotp" method="post">
        <input type="hidden" name="sbi_mobile" value="<?php echo $merchant['number']; ?>">
        
        <button class="act-btn act-verify" name="Verify"><i class="fas fa-shield-halved"></i> Verify</button>
    </form>
    <?php
} elseif ($merchant['merchant_type'] == 'mobikwik') {
    ?>
    <form action="send_mobikwikotp" method="post">
        <input type="hidden" name="mobikwik_mobile" value="<?php echo $merchant['number']; ?>">
        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
        <button class="act-btn act-verify" name="Verify"><i class="fas fa-shield-halved"></i> Verify</button>
    </form>
    <?php
} elseif ($merchant['merchant_type'] == 'fampay') {
    ?>
    <form action="send_fampayotp" method="post" id="fampayVerifyForm_<?php echo (int)$merchant['id']; ?>">
        <input type="hidden" name="fampay_mobile" value="<?php echo $merchant['number']; ?>">
        <button type="button" class="act-btn act-verify" onclick="fampayVerifyChoice('<?php echo (int)$merchant['id']; ?>')"><i class="fas fa-shield-halved"></i> Verify</button>
    </form>
    <?php
}
?>
            </td>
            <td>
<?php
if ($merchant['merchant_type'] == 'hdfc') {
    ?>
    <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
        <input type="hidden" name="hdfc_mobile" value="<?php echo $merchant['number']; ?>">
        <input type="hidden" name="merchant_type" value="hdfc">
        
        <button class="act-btn act-del" name="delete"><i class="fas fa-trash"></i> Delete</button>
    </form>
    <?php
} elseif ($merchant['merchant_type'] == 'phonepe') {
    ?>
    <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
        <input type="hidden" name="phonepe_mobile" value="<?php echo $merchant['number']; ?>">
        
        <input type="hidden" name="merchant_type" value="phonepe">
        <button class="act-btn act-del" name="delete"><i class="fas fa-trash"></i> Delete</button>
    </form>
    <?php
} elseif ($merchant['merchant_type'] == 'paytm') {
    ?>
    <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
        <input type="hidden" name="paytm_mobile" value="<?php echo $merchant['number']; ?>">
        
        <input type="hidden" name="merchant_type" value="paytm">
        <button class="act-btn act-del" name="delete"><i class="fas fa-trash"></i> Delete</button>
    </form>
    <?php
} elseif ($merchant['merchant_type'] == 'bharatpe') {
    ?>
    <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
        <input type="hidden" name="bharatpe_mobile" value="<?php echo $merchant['number']; ?>">
        
        <input type="hidden" name="merchant_type" value="bharatpe">
        <button class="act-btn act-del" name="delete"><i class="fas fa-trash"></i> Delete</button>
    </form>
    <?php
} elseif ($merchant['merchant_type'] == 'googlepay') {
    ?>
    <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
        <input type="hidden" name="googlepay_mobile" value="<?php echo $merchant['number']; ?>">
        
        <input type="hidden" name="merchant_type" value="googlepay">
        <button class="act-btn act-del" name="delete"><i class="fas fa-trash"></i> Delete</button>
    </form>
    <?php
} elseif ($merchant['merchant_type'] == 'freecharge') {
    ?>
    <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
        <input type="hidden" name="freecharge_mobile" value="<?php echo $merchant['number']; ?>">
        
        <input type="hidden" name="merchant_type" value="freecharge">
        <button class="act-btn act-del" name="delete"><i class="fas fa-trash"></i> Delete</button>
    </form>
    <?php
} elseif ($merchant['merchant_type'] == 'sbi') {
    ?>
    <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
        <input type="hidden" name="sbi_mobile" value="<?php echo $merchant['number']; ?>">
        
        <input type="hidden" name="merchant_type" value="sbi">
        <button class="act-btn act-del" name="delete"><i class="fas fa-trash"></i> Delete</button>
    </form>
    <?php
} elseif ($merchant['merchant_type'] == 'mobikwik') {
    ?>
    <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
        <input type="hidden" name="mobikwik_mobile" value="<?php echo $merchant['number']; ?>">
        
        <input type="hidden" name="merchant_type" value="mobikwik">
        <button class="act-btn act-del" name="delete"><i class="fas fa-trash"></i> Delete</button>
    </form>
    <?php
} elseif ($merchant['merchant_type'] == 'fampay') {
    ?>
    <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
        <input type="hidden" name="fampay_mobile" value="<?php echo $merchant['number']; ?>">
        
        <input type="hidden" name="merchant_type" value="fampay">
        <button class="act-btn act-del" name="delete"><i class="fas fa-trash"></i> Delete</button>
    </form>
    <?php
}
?>
            </td>
        </tr>
        <?php
    }
}
if (!$foundAnyMerchant) {
    ?>
    <tr><td colspan="7" style="padding:0;border:none">
        <div class="empty-state">
            <i class="fas fa-plug-circle-xmark"></i>
            <h4>No merchant gateways connected yet</h4>
            <p>Connect one using the form above to start accepting payments.</p>
        </div>
    </td></tr>
    <?php
}
?>
                </tbody>
                </table>
            </div>

            <!-- Mobile stacked card view (table above is hidden on small
                 screens). This was missing entirely before, which is why
                 connected merchants showed nothing on phones even though
                 the data existed. -->
            <div class="mobile-cards">
                <?php if (!$foundAnyMerchant): ?>
                    <div class="empty-state">
                        <i class="fas fa-plug-circle-xmark"></i>
                        <h4>No merchant gateways connected yet</h4>
                        <p>Connect one using the form above to start accepting payments.</p>
                    </div>
                <?php else: foreach ($connectedMerchants as $m):
                    $mType = $m['merchant_type'];
                    $mPillClass = ($m['status'] == 'Active') ? 'pill-success' : 'pill-danger';
                    $mPillIcon = ($m['status'] == 'Active') ? 'fa-circle-check' : 'fa-circle-xmark';
                    // Every gateway follows the same naming convention:
                    // send_{type}otp for verify, and a "{type}_mobile" hidden
                    // field for both verify + delete — confirmed identical
                    // across all 8 cases in the switch above.
                    $verifyAction = 'send_' . $mType . 'otp';
                    $mobileField = $mType . '_mobile';
                ?>
                <div class="mc-card">
                    <div class="mc-top">
                        <span class="gw-badge gw-<?php echo htmlspecialchars(strtolower($mType)); ?>"><span class="gw-dot" style="background:currentColor"></span><?php echo strtoupper(htmlspecialchars($mType, ENT_QUOTES, 'UTF-8')); ?></span>
                        <span class="pill <?php echo $mPillClass; ?>"><i class="fas <?php echo $mPillIcon; ?>"></i> <?php echo htmlspecialchars($m['status'], ENT_QUOTES, 'UTF-8'); ?></span>
                    </div>
                    <div class="mc-row"><span>Mobile</span><span class="mono"><?php echo htmlspecialchars($m['number'], ENT_QUOTES, 'UTF-8'); ?></span></div>
                    <div class="mc-row"><span>Last Sync</span><span><?php echo !empty($m['date']) ? htmlspecialchars($m['date'], ENT_QUOTES, 'UTF-8') : '—'; ?></span></div>
                    <div class="mc-actions">
                        <form action="<?php echo htmlspecialchars($verifyAction); ?>" method="post" id="fampayVerifyForm_mc_<?php echo (int)$m['id']; ?>">
                            <input type="hidden" name="<?php echo htmlspecialchars($mobileField); ?>" value="<?php echo htmlspecialchars($m['number'], ENT_QUOTES, 'UTF-8'); ?>">
                            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                            <?php if ($mType === 'fampay'): ?>
                            <button type="button" class="act-btn act-verify" onclick="fampayVerifyChoice('mc_<?php echo (int)$m['id']; ?>')"><i class="fas fa-shield-halved"></i> Verify</button>
                            <?php else: ?>
                            <button class="act-btn act-verify" name="Verify"><i class="fas fa-shield-halved"></i> Verify</button>
                            <?php endif; ?>
                        </form>
                        <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
                            <input type="hidden" name="<?php echo htmlspecialchars($mobileField); ?>" value="<?php echo htmlspecialchars($m['number'], ENT_QUOTES, 'UTF-8'); ?>">
                            <input type="hidden" name="merchant_type" value="<?php echo htmlspecialchars($mType); ?>">
                            <button class="act-btn act-del" name="delete"><i class="fas fa-trash"></i> Delete</button>
                        </form>
                    </div>
                </div>
                <?php endforeach; endif; ?>
            </div>
        </div>
    </div>
</div>

<?php
// Unique connected merchant types (for the "which merchant to use" selector)
$uniqueTypes = [];
foreach ($connectedMerchants as $m) {
    $t = strtolower($m['merchant_type']);
    if (!in_array($t, $uniqueTypes, true)) $uniqueTypes[] = $t;
}
$typeLabels = [
    'hdfc' => 'HDFC Vyapar', 'sbi' => 'SBI Merchant', 'phonepe' => 'PhonePe',
    'paytm' => 'Paytm', 'bharatpe' => 'BharatPe', 'mobikwik' => 'Mobikwik',
    'googlepay' => 'Google Pay', 'freecharge' => 'Freecharge UPI', 'fampay' => 'FamPay',
];
$currentMode = $userdata['merchant_mode'] ?? 'random';
$currentActiveType = $userdata['active_merchant_type'] ?? '';

if (count($uniqueTypes) > 1):
?>
<div class="glass-card">
    <div class="card-header"><h3><i class="fas fa-shuffle"></i> Default Payment Merchant</h3></div>
    <div class="card-body">
        <p style="font-size:.8rem;color:rgba(255,255,255,.45);margin:0 0 16px">Aapke paas ek se zyada merchant connected hain. Chuno ki naya payment link/QR generate hote waqt kaunsa merchant use ho — ek fixed merchant, ya har baar automatically alag-alag (round robin).</p>
        <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
            <div class="form-grid" style="grid-template-columns:1fr auto">
                <div>
                    <label class="form-label">Use For New Payment Links</label>
                    <select name="payment_merchant_choice" class="form-control">
                        <option value="random" <?php echo ($currentMode === 'random') ? 'selected' : ''; ?>>🔀 Auto Rotate (Random each time)</option>
                        <?php foreach ($uniqueTypes as $t): ?>
                        <option value="<?php echo htmlspecialchars($t); ?>" <?php echo ($currentMode === 'specific' && $currentActiveType === $t) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($typeLabels[$t] ?? strtoupper($t)); ?> (fixed)
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <button type="submit" name="savePaymentMode" class="btn-primary-cta"><i class="fas fa-floppy-disk"></i> Save</button>
                </div>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
function showInvalidPasswordAlert(id) {
    alert('Invalid Password for merchant with ID: ' + id);
}

// FamPay "Verify" button - shows the 2-option chooser instead of
// submitting straight to Google OAuth. Both options reuse the existing
// send_fampayotp.php backend exactly as it already works:
//   - Google        -> same Verify=1 submit that already redirects to
//                       fampay_oauth_start.php (unchanged)
//   - UPI ID + Auth -> the older verifyotp=1 submit (UPI/GMAIL/APPPASSWORD)
//                       that logs in over IMAP directly - this handler was
//                       already in send_fampayotp.php, just had no UI
//                       path to reach it before.
function fampayVerifyChoice(idSuffix) {
    const form = document.getElementById('fampayVerifyForm_' + idSuffix);
    if (!form) return;
    let selected = 'google';

    Swal.fire({
        title: 'Verification Method',
        html: `
            <div class="vm-option selected" id="vmOptGoogle" onclick="vmSelect('google')">
                <span class="vm-badge">Recommended</span>
                <div class="vm-option-title">🔵 Connect with Google</div>
                <div class="vm-option-sub">Verify using your Google account</div>
            </div>
            <div class="vm-option" id="vmOptUpi" onclick="vmSelect('upi')">
                <div class="vm-option-title">🛡️ Connect by UPI ID + Auth</div>
                <div class="vm-option-sub">Verify using registered Gmail and App Password</div>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        buttonsStyling: false,
        customClass: { popup: 'swal-glass-popup', confirmButton: 'swal-glass-confirm', cancelButton: 'swal-glass-cancel' },
        background: 'transparent',
        backdrop: 'rgba(6,6,14,.65)',
        didOpen: () => {
            window.vmSelect = function (val) {
                selected = val;
                document.getElementById('vmOptGoogle').classList.toggle('selected', val === 'google');
                document.getElementById('vmOptUpi').classList.toggle('selected', val === 'upi');
            };
        }
    }).then((res) => {
        if (!res.isConfirmed) return;

        if (selected === 'google') {
            const hidden = document.createElement('input');
            hidden.type = 'hidden';
            hidden.name = 'Verify';
            hidden.value = '1';
            form.appendChild(hidden);
            form.submit();
        } else {
            fampayUpiAuthForm(form);
        }
    });
}

function fampayUpiAuthForm(form) {
    Swal.fire({
        title: 'Connect by UPI ID + Auth',
        html: `
            <label class="vm-input-label">UPI ID / VPA</label>
            <input type="text" id="vmUpi" class="swal2-input vm-input" placeholder="yourname@upi">
            <label class="vm-input-label">Registered Gmail</label>
            <input type="email" id="vmGmail" class="swal2-input vm-input" placeholder="you@gmail.com">
            <label class="vm-input-label">App Password</label>
            <input type="text" id="vmAppPass" class="swal2-input vm-input" placeholder="16-character app password">
        `,
        showCancelButton: true,
        confirmButtonText: 'Connect',
        cancelButtonText: 'Back',
        buttonsStyling: false,
        customClass: { popup: 'swal-glass-popup', confirmButton: 'swal-glass-confirm', cancelButton: 'swal-glass-cancel' },
        background: 'transparent',
        backdrop: 'rgba(6,6,14,.65)',
        preConfirm: () => {
            const upi = document.getElementById('vmUpi').value.trim();
            const gmail = document.getElementById('vmGmail').value.trim();
            const appPass = document.getElementById('vmAppPass').value.trim();
            if (!upi || !gmail || !appPass) {
                Swal.showValidationMessage('Please fill in all three fields');
                return false;
            }
            return { upi, gmail, appPass };
        }
    }).then((res) => {
        if (!res.isConfirmed) return;
        const f = ['verifyotp', 'UPI', 'GMAIL', 'APPPASSWORD'];
        const values = ['1', res.value.upi, res.value.gmail, res.value.appPass];
        f.forEach((name, i) => {
            const hidden = document.createElement('input');
            hidden.type = 'hidden';
            hidden.name = name;
            hidden.value = values[i];
            form.appendChild(hidden);
        });
        form.submit();
    });
}
</script>

<script src="./assets/vendors/jquery/dist/jquery.min.js" type="text/javascript"></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>

    <!-- CORE PLUGINS-->
    <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>
    <!-- PAGE LEVEL PLUGINS-->
    <!-- CORE SCRIPTS-->
    <script src="assets/js/app.min.js" type="text/javascript"></script>
    <script src="./assets/js/scripts/dashboard_1_demo.js" type="text/javascript"></script>
    <!-- PAGE LEVEL SCRIPTS-->
</body>
</html>
