<?php
require_once '../includes/config.php';
requireAdmin();
$db = getDB();

// Create table
try {
    $db->exec("CREATE TABLE IF NOT EXISTS user_service_access (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        service VARCHAR(30) NOT NULL,
        is_enabled TINYINT(1) DEFAULT 1,
        UNIQUE KEY uq_user_svc (user_id, service)
    )");
} catch(Exception $e) {}

$msg = null;
if (isset($_GET['ok'])) $msg = ['ok'=>true,'text'=>'✅ Saved successfully!'];

// Save user services
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_user_svc'])) {
    $uid = intval($_POST['user_id']);
    $svcs = ['topup','drive','international','cards','manual_drive','mbanking','deposit','bill_pay'];
    foreach($svcs as $s) {
        $on = isset($_POST['svc_'.$s]) ? 1 : 0;
        $db->prepare("INSERT INTO user_service_access (user_id,service,is_enabled) VALUES (?,?,?) ON DUPLICATE KEY UPDATE is_enabled=?")
           ->execute([$uid,$s,$on,$on]);
    }
    $msg = ['ok'=>true,'text'=>'Services updated!'];
    header('Location: user_services.php?ok=1'); exit;
}

// Search
$search = sanitize($_GET['search'] ?? '');
$where  = $search ? "WHERE name LIKE ? OR phone LIKE ? OR username LIKE ?" : "";
$params = $search ? ["%$search%","%$search%","%$search%"] : [];

$users = $db->prepare("SELECT id,name,username,phone,role,status FROM users $where ORDER BY id DESC LIMIT 50");
$users->execute($params);
$users = $users->fetchAll();

$svcDefs = ['topup'=>'📱 Topup','drive'=>'⚡ Drive','international'=>'🌍 Intl','cards'=>'🎴 Cards','manual_drive'=>'📦 Manual Drive','mbanking'=>'🏦 M.Banking','deposit'=>'💰 Deposit','bill_pay'=>'🧾 Bill Pay'];

// Load all user services
$allAccess = $db->query("SELECT user_id, service, is_enabled FROM user_service_access")->fetchAll();
$accessMap = [];
foreach($allAccess as $a) $accessMap[$a['user_id']][$a['service']] = $a['is_enabled'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>User Services</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="../assets/css/admin.css">
<style>
.card{background:white;border-radius:14px;box-shadow:0 2px 8px rgba(0,0,0,0.06);margin-bottom:16px;overflow:hidden}
.card-h{padding:14px 18px;font-size:14px;font-weight:700;border-bottom:1px solid #f5f5f5;display:flex;align-items:center;gap:8px}
.alert{padding:11px 16px;border-radius:10px;font-size:13px;font-weight:600;margin-bottom:14px}
.alert-ok{background:#f0fff4;color:#276749;border:1px solid #c6f6d5}
.search-box{display:flex;gap:8px;padding:12px 16px;border-bottom:1px solid #f5f5f5}
.search-box input{flex:1;padding:9px 12px;border:2px solid #e8ecf4;border-radius:10px;font-size:13px;outline:none}
.search-box button{padding:9px 16px;background:var(--primary);color:white;border:none;border-radius:10px;font-size:13px;font-weight:700;cursor:pointer}
.user-row{padding:12px 18px;display:flex;align-items:center;gap:12px;border-bottom:1px solid #f8f8f8;cursor:pointer;transition:0.15s}
.user-row:hover{background:#f8faff}
.user-row.open{background:#f0f4ff}
.uname{font-size:13px;font-weight:700;color:#222}
.usub{font-size:11px;color:#aaa;margin-top:2px}
.svc-form{display:none;padding:14px 18px;background:#fafbff;border-bottom:1px solid #f0f0f0}
.svc-form.open{display:block}
.svc-grid{display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:8px;margin-bottom:12px}
.svc-item{display:flex;align-items:center;justify-content:space-between;padding:8px 12px;border-radius:10px;border:2px solid #f0f0f0;background:white;font-size:12px;font-weight:700;cursor:pointer}
.svc-item.on{border-color:#c6f6d5;background:#f0fff4;color:#276749}
.svc-item.off{border-color:#fed7d7;background:#fff5f5;color:#e53e3e}
.tog{width:36px;height:20px;border-radius:10px;position:relative;transition:0.2s;flex-shrink:0}
.tog.on{background:#38a169}.tog.off{background:#ddd}
.tog-th{position:absolute;top:2px;width:16px;height:16px;border-radius:50%;background:white;transition:0.2s;box-shadow:0 1px 3px rgba(0,0,0,0.2)}
.tog.on .tog-th{left:18px}.tog.off .tog-th{left:2px}
.save-btn{background:var(--primary);color:white;border:none;padding:9px 20px;border-radius:10px;font-size:13px;font-weight:700;cursor:pointer}
.badge{font-size:10px;padding:2px 8px;border-radius:20px;font-weight:700}
.b-active{background:#f0fff4;color:#276749}.b-inactive{background:#fff5f5;color:#e53e3e}
</style>
</head>
<body>
<?php include '../includes/admin_sidebar.php'; ?>
<div class="main">
<div class="topbar">
    <div class="topbar-left">
        <button class="menu-toggle" onclick="openSidebar()"><i class="fas fa-bars"></i></button>
        <span class="topbar-title">🔧 User Services</span>
    </div>
</div>
<div class="content">
<?php if($msg): ?><div class="alert alert-ok">✅ <?= htmlspecialchars($msg['text']) ?></div><?php endif; ?>

<div class="card">
    <div class="card-h"><i class="fas fa-users" style="color:var(--primary)"></i> User Service Access Control</div>
    <form method="GET" class="search-box">
        <input name="search" value="<?= htmlspecialchars($search) ?>" placeholder="Search name, phone, username...">
        <button type="submit"><i class="fas fa-search"></i></button>
    </form>

    <?php foreach($users as $u):
        $uAccess = $accessMap[$u['id']] ?? [];
        // Count enabled services
        $enabledCount = 0;
        foreach(array_keys($svcDefs) as $s) {
            $on = isset($uAccess[$s]) ? $uAccess[$s] : 1; // default on
            if($on) $enabledCount++;
        }
    ?>
    <div class="user-row" onclick="toggleUser(<?= $u['id'] ?>)" id="urow<?= $u['id'] ?>">
        <div style="width:38px;height:38px;border-radius:10px;background:#f0f4ff;display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0">
            <i class="fas fa-user" style="color:var(--primary)"></i>
        </div>
        <div style="flex:1;min-width:0">
            <div class="uname"><?= htmlspecialchars($u['name']) ?> <span class="badge b-<?= $u['status'] ?>"><?= ucfirst($u['status']) ?></span></div>
            <div class="usub"><?= $u['phone'] ?> · @<?= $u['username'] ?></div>
        </div>
        <div style="font-size:12px;color:#aaa;margin-right:8px"><?= $enabledCount ?>/<?= count($svcDefs) ?> services</div>
        <i class="fas fa-chevron-down" id="uico<?= $u['id'] ?>" style="color:#ddd;font-size:11px;transition:0.2s"></i>
    </div>

    <div class="svc-form" id="uform<?= $u['id'] ?>">
        <form method="POST">
            <input type="hidden" name="save_user_svc" value="1">
            <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
            <div class="svc-grid">
            <?php foreach($svcDefs as $key=>$label):
                $on = isset($uAccess[$key]) ? (bool)$uAccess[$key] : true;
            ?>
            <label class="svc-item <?= $on?'on':'off' ?>" id="si_<?= $u['id'] ?>_<?= $key ?>" onclick="toggleSvc(this,'<?= $u['id'] ?>','<?= $key ?>')">
                <span><?= $label ?></span>
                <input type="checkbox" name="svc_<?= $key ?>" value="1" <?= $on?'checked':'' ?> style="display:none">
                <div class="tog <?= $on?'on':'off' ?>" id="tog_<?= $u['id'] ?>_<?= $key ?>">
                    <div class="tog-th"></div>
                </div>
            </label>
            <?php endforeach; ?>
            </div>
            <button type="submit" class="save-btn"><i class="fas fa-save"></i> Save Changes</button>
        </form>
    </div>
    <?php endforeach; ?>
    <?php if(empty($users)): ?><div style="text-align:center;padding:30px;color:#ccc">No users found</div><?php endif; ?>
</div>

</div></div>

<script>
function toggleUser(id) {
    const form = document.getElementById('uform'+id);
    const row  = document.getElementById('urow'+id);
    const ico  = document.getElementById('uico'+id);
    const open = form.classList.toggle('open');
    row.classList.toggle('open', open);
    ico.style.transform = open ? 'rotate(180deg)' : '';
}
function toggleSvc(lbl, uid, key) {
    const cb  = lbl.querySelector('input[type=checkbox]');
    const tog = document.getElementById('tog_'+uid+'_'+key);
    const on  = !cb.checked;
    cb.checked = on;
    lbl.className = 'svc-item '+(on?'on':'off');
    tog.className = 'tog '+(on?'on':'off');
    event.preventDefault();
}
</script>
</body>
</html>
