<?php include "header.php"; ?>
<?php
include_once __DIR__ . '/../includes/merchant_lib.php';
include_once __DIR__ . '/../includes/subscription_lib.php';

$user_id = $userdata['id'];

// Save merchant mode / specific choice
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['save_mode'])) {
    $mode = in_array($_POST['merchant_mode'], ['specific', 'all', 'random']) ? $_POST['merchant_mode'] : 'all';
    $activeType = $_POST['active_merchant_type'] ?? null;

    $stmt = $conn->prepare("UPDATE users SET merchant_mode = ?, active_merchant_type = ? WHERE id = ?");
    $stmt->bind_param("ssi", $mode, $activeType, $user_id);
    $stmt->execute();
    $stmt->close();

    echo '<script>Swal.fire({title:"Saved!", text:"Merchant routing preference updated.", icon:"success"}).then(()=>{ window.location.href = "merchant_settings"; });</script>';
}

// Toggle connect/disconnect for a merchant type (Yes/No on the *_connected column)
if (isset($_GET['toggle_connect'])) {
    $type = preg_replace('/[^a-z]/', '', $_GET['toggle_connect']);
    $allowedTypes = ['hdfc','phonepe','paytm','bharatpe','googlepay','freecharge','sbi','mobikwik','fampay'];
    if (in_array($type, $allowedTypes, true)) {
        $col = $type . '_connected';
        $conn->query("UPDATE users SET `$col` = IF(`$col`='Yes','No','Yes') WHERE id = " . (int)$user_id);
    }
    echo '<script>window.location.href = "merchant_settings";</script>';
    exit;
}

$fresh = $conn->query("SELECT * FROM users WHERE id = " . (int)$user_id)->fetch_assoc();
$connectedMap = buildConnectedMapFromUserRow($fresh);
$cashierLimit = getCashierLimit($conn, $user_id);
$connectedCount = count(array_filter($connectedMap, fn($v) => $v === 'Yes'));

$labels = [
    'hdfc' => 'HDFC Vyapar', 'phonepe' => 'PhonePe', 'paytm' => 'Paytm',
    'bharatpe' => 'BharatPe', 'googlepay' => 'Google Pay', 'freecharge' => 'FreeCharge',
    'sbi' => 'SBI', 'mobikwik' => 'Mobikwik', 'fampay' => 'FamPay',
];
?>

<div class="page-heading">
    <h1 class="page-title">Merchant Routing Settings</h1>
</div>
<div class="page-content fade-in-up">
<div class="ibox"><div class="ibox-body"><div class="card m-t-20 m-b-20"><div class="card-body">

<p>Cashier limit on your current plan: <b><?= $cashierLimit ?></b> &nbsp;|&nbsp; Currently connected: <b><?= $connectedCount ?></b></p>

<form method="POST" action="" class="mb-4">
    <div class="row">
        <div class="col-md-4 mb-3">
            <label>Merchant Selection Mode</label>
            <select name="merchant_mode" id="merchant_mode" class="form-control" onchange="document.getElementById('specificWrap').style.display = this.value==='specific' ? 'block' : 'none';">
                <option value="all" <?= ($fresh['merchant_mode'] ?? 'all') == 'all' ? 'selected' : '' ?>>All connected (use whichever is marked Active)</option>
                <option value="specific" <?= ($fresh['merchant_mode'] ?? '') == 'specific' ? 'selected' : '' ?>>Specific merchant only</option>
                <option value="random" <?= ($fresh['merchant_mode'] ?? '') == 'random' ? 'selected' : '' ?>>Random (rotate every transaction)</option>
            </select>
        </div>
        <div class="col-md-4 mb-3" id="specificWrap" style="<?= ($fresh['merchant_mode'] ?? '') == 'specific' ? '' : 'display:none;' ?>">
            <label>Which merchant to always use</label>
            <select name="active_merchant_type" class="form-control">
                <?php foreach ($labels as $type => $label): if ($connectedMap[$type] !== 'Yes') continue; ?>
                    <option value="<?= $type ?>" <?= ($fresh['active_merchant_type'] ?? '') == $type ? 'selected' : '' ?>><?= $label ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-4 mb-3 d-flex align-items-end">
            <button type="submit" name="save_mode" class="btn btn-primary">Save Preference</button>
        </div>
    </div>
</form>

<h5>Connected Merchants</h5>
<table class="table">
    <thead><tr><th>Merchant</th><th>Status</th><th>Action</th></tr></thead>
    <tbody>
    <?php foreach ($labels as $type => $label): ?>
        <tr>
            <td><?= $label ?></td>
            <td><?= $connectedMap[$type] === 'Yes' ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Not connected</span>' ?></td>
            <td>
                <?php if ($connectedMap[$type] === 'Yes'): ?>
                    <button class="btn btn-sm btn-danger" onclick="Swal.fire({title:'Disconnect <?= $label ?>?', icon:'warning', showCancelButton:true, confirmButtonText:'Disconnect'}).then(r=>{if(r.isConfirmed) window.location.href='merchant_settings?toggle_connect=<?= $type ?>'})">Disconnect</button>
                <?php else: ?>
                    <a href="connect_merchant" class="btn btn-sm btn-success">Connect via Connect Merchant page</a>
                <?php endif; ?>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>

<p class="text-muted small">Note: your plan allows connecting up to <b><?= $cashierLimit ?></b> merchant account(s) at a time. Disconnect one before connecting a new one if you're at the limit.</p>

</div></div></div></div></div>
</body>
<script src="./assets/vendors/jquery/dist/jquery.min.js"></script>
<script src="assets/js/core/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="assets/js/app.min.js"></script>
</html>
