<?php
session_start();
require_once '../config.php';
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../login.php");
    exit;
}

// Handle Toggle Status (Aktif/Nonaktif)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_status_id'])) {
    $toggle_id = (int)$_POST['toggle_status_id'];
    $new_status = $_POST['set_status'] === 'aktif' ? 'nonaktif' : 'aktif';
    $stmt_toggle = $pdo->prepare("UPDATE pelanggan SET status = ? WHERE id = ?");
    $stmt_toggle->execute([$new_status, $toggle_id]);
    header("Location: manajemen_pelanggan.php");
    exit;
}

// Handle Hapus
if (isset($_GET['hapus'])) {
    $id_hapus = (int)$_GET['hapus'];
    $pdo->prepare("DELETE FROM pelanggan WHERE id = ?")->execute([$id_hapus]);
    header("Location: manajemen_pelanggan.php");
    exit;
}

// Ambil Data Pelanggan
$stmt = $pdo->query("SELECT * FROM pelanggan ORDER BY nama ASC");
$pelanggans = $stmt->fetchAll(PDO::FETCH_ASSOC);

$jumlah_semua = count($pelanggans);
$jumlah_aktif = 0;
$jumlah_nonaktif = 0;

foreach ($pelanggans as &$p) {
    if ($p['status'] === 'aktif') $jumlah_aktif++;
    else $jumlah_nonaktif++;
}
unset($p);
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Data Pelanggan - SPAM</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
body { background:#f8f9fa; font-family:'Segoe UI'; }
.bg-header{
    background: linear-gradient(135deg, #3A7CA5 0%, #2C5F7D 100%);
    color:white;
    padding:18px;
    border-bottom-left-radius:20px;
    border-bottom-right-radius:20px;
}
.card-pelanggan{
    border:none;
    border-radius:15px;
    box-shadow:0 2px 10px rgba(0,0,0,0.05);
    margin-bottom:12px;
    position:relative;
}
.card-nonaktif{ background:#e2e3e5 !important; }
.badge-nonaktif{
    position:absolute;
    top:10px;
    right:12px;
    background:#dc3545;
    color:white;
    font-size:11px;
    padding:4px 8px;
    border-radius:12px;
    font-weight:600;
}
.btn-catat{
    border-radius:20px;
    border:1px solid #3A7CA5;
    color:#3A7CA5;
    font-size:13px;
    padding:5px 15px;
    text-decoration:none;
}
.dropdown-toggle::after{ display:none; }
.search-sticky{
    position:sticky;
    top:0;
    background:#f8f9fa;
    z-index:100;
    padding-bottom:10px;
}
.search-wa{
    background:#f0f2f5;
    border-radius:25px;
    padding:10px 15px;
    display:flex;
    align-items:center;
}
.search-wa i{color:#667781;}
.search-wa input{
    border:none;
    background:transparent;
    width:100%;
    outline:none;
    font-size:15px;
    margin-left:8px;
}
.filter-scroll{
    overflow-x:auto;
    overflow-y:hidden;
    -webkit-overflow-scrolling:touch;
    scrollbar-width:none;
    margin-top:10px;
    padding-bottom:2px;
}
.filter-scroll::-webkit-scrollbar{ display:none; }
.filter-bar{ display:flex; gap:8px; flex-wrap:nowrap; width:max-content; min-width:100%; }
.filter-btn{
    border:none;
    background:#e9edef;
    padding:6px 14px;
    border-radius:20px;
    font-size:13px;
    white-space:nowrap;
    flex:0 0 auto;
}
.filter-btn.active{ background:#3A7CA5; color:white; }
.dropdown-menu form { margin: 0; }
.dropdown-menu button.dropdown-item { background: none; border: none; width: 100%; text-align: left; }
</style>
</head>
<body>
<div class="bg-header shadow-sm">
    <div class="container d-flex justify-content-between align-items-center">
        <a href="dashboard.php" class="text-white"><i class="fa fa-arrow-left"></i></a>
        <h5 class="mb-0 fw-bold">Data Pelanggan</h5>
        <a href="tambah_pelanggan.php" class="btn btn-light btn-sm rounded-pill fw-bold">+ Tambah</a>
    </div>
</div>

<div class="container pb-5">
    <div class="search-sticky">
        <div class="search-wa">
            <i class="fa fa-search"></i>
            <input type="text" id="smartSearch" placeholder="Cari nama pelanggan atau ID meteran..." autocomplete="off">
        </div>
        <div class="filter-scroll">
            <div class="filter-bar">
                <button class="filter-btn active" data-filter="semua">Semua (<?= $jumlah_semua ?>)</button>
                <button class="filter-btn" data-filter="aktif">Aktif (<?= $jumlah_aktif ?>)</button>
                <button class="filter-btn" data-filter="nonaktif">Nonaktif (<?= $jumlah_nonaktif ?>)</button>
            </div>
        </div>
    </div>

    <div class="row mt-3" id="hasilPelanggan">
        <?php foreach($pelanggans as $p): ?>
        <div class="col-12 pelanggan-item"
             data-nama="<?= strtolower(htmlspecialchars($p['nama'], ENT_QUOTES)) ?>"
             data-meteran="<?= strtolower(htmlspecialchars($p['id_meteran'], ENT_QUOTES)) ?>"
             data-status="<?= $p['status'] ?>">
            
            <div class="card card-pelanggan <?= ($p['status'] === 'nonaktif' ? 'card-nonaktif' : '') ?>">
                <div class="card-body">
                    <?php if($p['status'] === 'nonaktif'): ?>
                        <div class="badge-nonaktif">NONAKTIF</div>
                    <?php endif; ?>
                    
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6 class="fw-bold mb-1"><?= strtoupper(htmlspecialchars($p['nama'])) ?></h6>
                            <small class="text-muted d-block mb-1">
                                <i class="fa fa-droplet text-primary"></i> ID: <?= htmlspecialchars($p['id_meteran']) ?> 
                                | <i class="fa fa-phone text-success"></i> <?= htmlspecialchars($p['no_hp'] ?: '-') ?>
                            </small>
                            <div class="small text-secondary">
                                <i class="fa fa-location-dot text-danger"></i> <?= htmlspecialchars($p['alamat']) ?>
                            </div>
                        </div>
                        <div class="dropdown">
                            <button class="btn btn-link text-secondary p-0 dropdown-toggle" data-bs-toggle="dropdown">
                                <i class="fa fa-ellipsis-v"></i>
                            </button>
                            <ul class="dropdown-menu dropdown-menu-end shadow border-0">
                                <li>
                                    <a class="dropdown-item" href="edit_pelanggan.php?id=<?= $p['id'] ?>">
                                        <i class="fa fa-edit text-warning"></i> Edit
                                    </a>
                                </li>
                                <li>
                                    <form method="POST" onsubmit="return confirm('Ubah status pelanggan ini?')">
                                        <input type="hidden" name="toggle_status_id" value="<?= $p['id'] ?>">
                                        <input type="hidden" name="set_status" value="<?= $p['status'] ?>">
                                        <button type="submit" class="dropdown-item">
                                            <i class="fa <?= ($p['status'] === 'nonaktif') ? 'fa-rotate-left text-success' : 'fa-user-slash text-secondary' ?>"></i>
                                            <?= ($p['status'] === 'nonaktif') ? 'Aktifkan Kembali' : 'Nonaktifkan' ?>
                                        </button>
                                    </form>
                                </li>
                                <li><hr class="dropdown-divider"></li>
                                <li>
                                    <a class="dropdown-item text-danger" href="?hapus=<?= $p['id'] ?>" onclick="return confirm('Yakin hapus data ini?')">
                                        <i class="fa fa-trash"></i> Hapus
                                    </a>
                                </li>
                            </ul>
                        </div>
                    </div>
                    
                    <div class="d-flex justify-content-end mt-2">
                        <?php if($p['status'] === 'aktif'): ?>
                            <a href="../petugas/catat_meteran.php?id=<?= $p['id'] ?>" class="btn-catat">
                                <i class="fa fa-pen-to-square me-1"></i> Catat Meteran
                            </a>
                        <?php else: ?>
                            <button class="btn-catat" style="border-color:#dc3545;color:#dc3545;" disabled>
                                Terkunci
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
const search=document.getElementById("smartSearch");
const items=document.querySelectorAll(".pelanggan-item");
let filter="semua";

document.querySelectorAll(".filter-btn").forEach(btn=>{
    btn.onclick=function(){
        document.querySelectorAll(".filter-btn").forEach(b=>b.classList.remove("active"));
        this.classList.add("active");
        filter=this.dataset.filter;
        filterData();
    };
});

search.addEventListener("keyup",filterData);

function filterData(){
    let keyword=search.value.toLowerCase();
    items.forEach(el=>{
        let nama=el.dataset.nama;
        let meteran=el.dataset.meteran;
        let status=el.dataset.status;
        
        let cocok = nama.includes(keyword) || meteran.includes(keyword);
        let cocokFilter = (filter=="semua") || (filter==status);
        
        el.style.display = (cocok && cocokFilter) ? "block" : "none";
    });
}
</script>
</body>
</html>