<?php
session_start();
include "koneksi.php";

// cek admin
$isAdmin = isset($_SESSION['role']) && $_SESSION['role'] === 'admin';

// ----- parameters search/pagination -----
$q = isset($_GET['q']) ? trim($_GET['q']) : '';
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 4;
$offset = ($page - 1) * $perPage;

// build WHERE
$where = "1=1";
if ($q !== '') {
    $q_esc = $koneksi->real_escape_string($q);
    $where .= " AND (nama_mitra LIKE '%$q_esc%' OR whatsapp LIKE '%$q_esc%' OR alamat LIKE '%$q_esc%')";
}

// count total
$countSql = "SELECT COUNT(*) as cnt FROM kontak_mitra WHERE $where";
$resCount = mysqli_query($koneksi, $countSql);
$rowC = mysqli_fetch_assoc($resCount);
$total = intval($rowC['cnt']);
$pages = max(1, ceil($total / $perPage));

// fetch page
$sql = "SELECT * FROM kontak_mitra WHERE $where ORDER BY id DESC LIMIT $perPage OFFSET $offset";
$res = mysqli_query($koneksi, $sql);
if (!$res) {
    die("DB Error: " . mysqli_error($koneksi));
}
?>
<!doctype html>
<html lang="id">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Daftar Kontak Mitra</title>
    <link rel="stylesheet" href="css/navbar.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

    <style>
        :root {
            --navy: #071733;
            --card: #233a6a;
            --gold: #ffd800;
        }

        /* Perbaikan: jangan pakai position: fixed */
        html,
        body {
            height: 100%;
            overflow: hidden;
            /* FIX: body tidak scroll */
            width: 100%;
        }


        body {
            margin: 0;
            font-family: Poppins, Arial;
            background: linear-gradient(180deg, var(--navy) 100%, #233a6a 70%);
            color: #fff;
            padding-bottom: 50px;
        }

        /* container aman untuk mobile */
        .container {
            max-width: 920px;
            margin: 0 auto;
            padding: 0 10px;
        }

        /* Card agar tidak mepet layar */
        .search-card,
        .list .contact-card {
            margin-left: 4px;
            margin-right: 4px;
        }

        /* AREA SCROLL KHUSUS LIST KONTAK */
        .scroll-area {
            height: calc(100dvh - 300px);
            /* Tinggi aman semua HP */
            overflow-y: auto;
            overflow-x: hidden;
            padding-bottom: 20px;
            border-radius: 5px;
        }

        /* SEARCH CARD */
        .search-card {
            padding: 16px;
            border-radius: 14px;
            background: #233a6a;
            border: 1px solid rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(10px);
            margin-bottom: 30px;
            position: sticky;
            top: 20px;
            z-index: 998;
        }

        /* Input style */
        .search-input {
            width: 100%;
            padding: 12px;
            border-radius: 12px;
            border: 2px solid rgba(255, 255, 255, 0.18);
            background: rgba(255, 255, 255, 0.12);
            color: #ffffff;
            margin-bottom: 10px;
            text-align: center;
            font-weight: 600;
            font-size: 14px;
        }

        .search-input::placeholder {
            color: rgba(255, 255, 255, 0.85);
            text-align: center;
            font-weight: 700;
            letter-spacing: 0.3px;
        }

        .btn-add {
            width: 100%;
            background: linear-gradient(#ffe680, #ffcc00);
            color: #071733;
            font-weight: 700;
            border: none;
            padding: 12px;
            border-radius: 12px;
        }

        /* GRID LIST */
        .list {
            display: grid;
            grid-template-columns: 1fr;
            gap: 12px
        }

        /* CONTACT CARD */
        .contact-card {
            display: flex;
            max-width: 100%;
            box-sizing: border-box;
            padding: 7px;
            border-radius: 15px;
            background: #233a6a;
            border: 1px solid rgba(255, 255, 255, 0.12);
            backdrop-filter: blur(10px);
            gap: 14px;
            align-items: center;
        }

        .contact-photo {
            width: 95px;
            height: 95px;
            border-radius: 14px;
            overflow: hidden;
            background: #0f1d3a;
            border: 3px solid rgba(255, 255, 255, 0.42);
            flex-shrink: 0;
        }

        .contact-photo img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .contact-info {
            flex: 1;
            overflow: hidden;
        }

        .contact-name {
            font-size: 14px;
            font-weight: 800;
            color: var(--gold);
            cursor: pointer;
            margin-bottom: 6px;

            /* Bikin teks panjang jadi "..." */
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;

            /* Atur lebar maksimal agar ellipsis muncul */
            max-width: 150px;
            /* boleh disesuaikan */
            display: block;
        }

        .wa-bubble-new {
            display: inline-flex;
            align-items: center;
            font-size: 14px;
            gap: 8px;
            padding: 8px 12px;
            border-radius: 10px;
            background: linear-gradient(90deg, #25d366, #1aa35b);
            color: white;
            font-weight: 100;
            margin-bottom: 5px;
            text-decoration: none;
            box-shadow: 0 3px 0 rgba(0, 0, 0, 0.25);
        }

        .map-link-new {
            margin-top: 6px;
            display: flex;
            gap: 6px;
            color: #d8e9ff;
            font-size: 14px;
            text-decoration: none;
        }

        /* ACTION BUTTONS RIGHT */
        .contact-actions {
            display: flex;
            flex-direction: column;
            flex-shrink: 0;
            gap: 8px;
        }

        .btn-edit-new,
        .btn-delete-new {
            padding: 8px 10px;
            border-radius: 5px;
            border: none;
            font-size: 10px;
            font-weight: 700;
            cursor: pointer;
            margin-right: 0px;

            display: flex;
            align-items: center;
            gap: 6px;

            /* 3D base */
            box-shadow: 0px 3px 0px rgba(0, 0, 0, 0.35);
            position: relative;
            transition: all 0.15s ease;
        }

        /* ----- HOVER (angkat sedikit) ----- */
        .btn-edit-new:hover,
        .btn-delete-new:hover {
            transform: translateY(-2px);
            box-shadow: 0px 5px 0px rgba(0, 0, 0, 0.35);
            filter: brightness(1.05);
        }

        /* ----- ACTIVE (ditekan) ----- */
        .btn-edit-new:active,
        .btn-delete-new:active {
            transform: translateY(3px);
            box-shadow: 0px 0px 0px rgba(0, 0, 0, 0.3);
            filter: brightness(0.95);
        }

        /* ----- EDIT BUTTON ----- */
        .btn-edit-new {
            background: #ffd800;
            color: #071733;
            background-image: linear-gradient(to top, rgba(0, 0, 0, 0.12), rgba(255, 255, 255, 0.25));
        }

        /* ----- DELETE BUTTON ----- */
        .btn-delete-new {
            background: #ff5c5c;
            color: #fff;
            background-image: linear-gradient(to top, rgba(0, 0, 0, 0.12), rgba(255, 255, 255, 0.22));
        }


        .empty {
            text-align: center;
            padding: 20px;
            opacity: 0.8
        }

        .pagination {
            display: flex;
            justify-content: center;
            gap: 10px;
            padding: 12px 0;
            margin-top: 10px;
        }

        .page-btn {
            height: 25px;
            padding: 0 14px;
            border-radius: 5px;

            display: flex;
            justify-content: center;
            align-items: center;

            background: rgba(255, 247, 247, 0.08);
            color: #dbe7ff;
            font-weight: 700;
            text-decoration: none;
            font-size: 14px;

            border: 1px solid rgba(255, 255, 255, 0.15);
            box-shadow: 0 3px 0 rgba(0, 0, 0, 0.3);

            transition: all .25s ease;
            backdrop-filter: blur(6px);
        }

        .page-btn:hover {
            background: rgba(255, 255, 255, 0.18);
            transform: translateY(-2px);
        }

        .page-btn.active {
            background: linear-gradient(145deg, #ffe680, #ffcc00);
            color: #071733;
            border: 1px solid #d1a700;
            box-shadow: 0 4px 0 #b89600;
            transform: translateY(-1px);
        }

        /* SweetAlert2 - Navy Glassmorphism + Margin */
        .swal2-popup {
            background: rgba(30, 45, 80, 0.35) !important;
            backdrop-filter: blur(14px) !important;
            -webkit-backdrop-filter: blur(14px) !important;
            /* Margin agar ada jarak dari sisi layar */
            margin-left: 500px !important;
            margin-right: 500px !important;
            border: 2px solid rgba(90, 120, 180, 0.4);
            border-radius: 16px;
            color: #ffffff !important;
            font-size: 16px;
            box-shadow: 0 100px 28px rgba(0, 0, 0, 0.35);
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        /* Judul popup */
        .swal2-title {
            font-size: 20px;
            color: #ffffffff;
            text-align: center;
        }

        /* Input fields */
        .swal2-input {
            width: 100%;
            max-width: 250px;
            margin: 8px auto;
            background-color: #1e2329 !important;
            color: #ffffff !important;
            border: 1px solid #444 !important;
            border-radius: 8px;
            padding: 10px 12px;
            box-sizing: border-box;
        }

        /* Base styling untuk semua tombol SweetAlert */
        .swal2-styled {
            padding: 14px 26px !important;
            font-size: 17px !important;
            font-weight: 700 !important;
            border-radius: 14px !important;
            backdrop-filter: blur(10px) !important;
            -webkit-backdrop-filter: blur(10px) !important;
            box-shadow:
                0 10px 18px rgba(0, 0, 0, 0.35),
                inset 0 5px 8px rgba(255, 255, 255, 0.22),
                inset 0 -5px 8px rgba(0, 0, 0, 0.30);
            transition: 0.22s ease !important;
        }

        /* Hover umum */
        .swal2-styled:hover {
            transform: translateY(-3px);
        }

        /* Active umum */
        .swal2-styled:active {
            transform: translateY(3px);
        }

        /* --------------------------- */
        /*  STAY (Hijau Glass)         */
        /* --------------------------- */
        .swal2-confirm {
            background: rgba(40, 150, 80, 0.45) !important;
            /* hijau transparan */
            border: 2px solid rgba(120, 230, 160, 0.5) !important;
            color: #fff !important;
            box-shadow:
                0 10px 18px rgba(0, 0, 0, 0.35),
                inset 0 6px 10px rgba(255, 255, 255, 0.20),
                inset 0 -6px 10px rgba(0, 0, 0, 0.35);
        }

        .swal2-confirm:hover {
            background: rgba(55, 180, 110, 0.55) !important;
        }

        /* --------------------------- */
        /*  OFF (Merah Glass)          */
        /* --------------------------- */
        .swal2-deny {
            background: rgba(180, 40, 60, 0.45) !important;
            /* merah transparan */
            border: 2px solid rgba(255, 150, 150, 0.5) !important;
            color: #fff !important;
        }

        .swal2-deny:hover {
            background: rgba(210, 55, 80, 0.55) !important;
        }

        /* --------------------------- */
        /*  Batal (Hitam Glass)        */
        /* --------------------------- */
        .swal2-cancel {
            background: rgba(20, 20, 20, 0.45) !important;
            /* hitam transparan */
            border: 2px solid rgba(180, 180, 180, 0.4) !important;
            color: #fff !important;
        }

        .swal2-cancel:hover {
            background: rgba(40, 40, 40, 0.55) !important;
        }


        /* Tombol shift 3D - Glass Navy Cembung */
        .swal-shift-btn {
            padding: 16px 20px;
            min-width: 80px;
            font-size: 18px;
            font-weight: 700;
            color: #ffffff;

            /* Tambahkan jarak antar tombol */
            margin: 0 6px;

            /* Glass navy */
            background: rgba(40, 60, 110, 0.45);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);

            border-radius: 18px;
            border: 2px solid rgba(180, 200, 255, 0.45);

            cursor: pointer;
            transition: 0.22s ease;

            /* --- Efek 3D tonjol keluar --- */
            box-shadow:
                0 12px 18px rgba(0, 0, 0, 0.45),
                inset 0 6px 10px rgba(255, 255, 255, 0.25),
                inset 0 -6px 10px rgba(0, 0, 0, 0.35),
                0 0 14px rgba(90, 120, 200, 0.5);
        }

        /* Hover: makin menonjol */
        .swal-shift-btn:hover {
            transform: translateY(-4px);
            box-shadow:
                0 16px 22px rgba(0, 0, 0, 0.55),
                inset 0 7px 11px rgba(255, 255, 255, 0.28),
                inset 0 -7px 11px rgba(0, 0, 0, 0.4),
                0 0 16px rgba(110, 140, 230, 0.6);
        }

        /* Active: ditekan */
        .swal-shift-btn:active {
            transform: translateY(3px);
            box-shadow:
                0 7px 10px rgba(0, 0, 0, 0.45),
                inset 0 3px 6px rgba(255, 255, 255, 0.18),
                inset 0 -4px 7px rgba(0, 0, 0, 0.35),
                0 0 12px rgba(90, 120, 200, 0.45);
        }

        /* Hilangkan garis animasi */
        .swal2-success-ring,
        .swal2-success-fix {
            background: none !important;
            display: none !important;
        }

        /* Hapus inner circle */
        .swal2-success-circular-line-left,
        .swal2-success-circular-line-right {
            display: none !important;
        }
    </style>
</head>

<body>
    <div class="container">

        <!-- SEARCH -->
        <div class="search-card">
            <input class="search-input"
                id="searchInput"
                type="search"
                placeholder="Cari mitra..."
                autocomplete="off"
                autocorrect="off"
                autocapitalize="off"
                spellcheck="false">

            <?php if ($isAdmin): ?>
                <button class="btn-add" onclick="location.href='tambah_mitra.php'">
                    <i class="fa fa-plus"></i> Tambah Kontak
                </button>
            <?php endif; ?>
        </div>

        <!-- LIST -->
        <div class="scroll-area">
            <div class="list" id="list">

                <?php if (mysqli_num_rows($res) == 0): ?>
                    <div class="empty">Tidak ada data mitra.</div>
                    <?php else: while ($row = mysqli_fetch_assoc($res)): ?>

                        <div class="contact-card">

                            <div class="contact-photo">
                                <?php $fp = "foto_mitra/" . $row['foto']; ?>
                                <img src="<?= (!empty($row['foto']) && file_exists($fp)) ? $fp : 'https://via.placeholder.com/300x300?text=No+Image' ?>">
                            </div>

                            <div class="contact-info">
                                <div class="contact-name"
                                    onclick="showDetail(
                         '<?= htmlspecialchars($row['nama_mitra']) ?>',
                         '<?= htmlspecialchars($row['whatsapp']) ?>',
                         '<?= htmlspecialchars($row['alamat']) ?>',
                         '<?= htmlspecialchars($row['maps_url']) ?>'
                    )">
                                    <?= htmlspecialchars($row['nama_mitra']) ?>
                                </div>

                                <a class="wa-bubble-new"
                                    target="_blank"
                                    href="https://wa.me/<?= preg_replace('/\D+/', '', $row['whatsapp']) ?>">
                                    <i class="fa fa-phone"></i> <?= $row['whatsapp'] ?>
                                </a>

                                <a class="map-link-new" target="_blank" href="<?= $row['maps_url'] ?>">
                                    <i class="fa fa-map-marker-alt"></i> Buka Google Maps
                                </a>
                            </div>

                            <?php if ($isAdmin): ?>
                                <div class="contact-actions">
                                    <button class="btn-edit-new" onclick="location.href='edit_mitra.php?id=<?= $row['id'] ?>'">
                                        <i class="fa fa-pen"></i>
                                    </button>

                                    <form method="post" action="hapus_mitra.php" onsubmit="return confirmDelete(this)">
                                        <input type="hidden" name="id" value="<?= $row['id'] ?>">
                                        <button type="submit" class="btn-delete-new">
                                            <i class="fa fa-trash"></i>
                                        </button>
                                    </form>
                                </div>
                            <?php endif; ?>

                        </div>

                <?php endwhile;
                endif; ?>

            </div> <!-- END .list -->
        </div> <!-- END .scroll-area -->

        <!-- PAGINATION DI SINI -->
        <div class="pagination">
            <?php
            $base = strtok($_SERVER["REQUEST_URI"], '?');
            $qParam = $q !== '' ? '&q=' . urlencode($q) : '';
            for ($p = 1; $p <= $pages; $p++):
                $active = $p == $page ? 'active' : '';
                $url = $base . '?page=' . $p . $qParam;
            ?>
                <a class="page-btn <?= $active ?>" href="<?= $url ?>"><?= $p ?></a>
            <?php endfor; ?>
        </div>
    </div>


    <script>
        // Detail popup
        function showDetail(nama, wa, alamat, maps) {
            Swal.fire({
                title: nama,
                html: `
            <div style="text-align:left;font-size:15px">
                <b>WhatsApp:</b><br>
                <a href="https://wa.me/${wa.replace(/\D+/g,'')}"
                   style="color:#25d366;font-weight:700" target="_blank">${wa}</a><br><br>

                <b>Alamat:</b><br>${alamat}<br><br>

                <a href="${maps}" target="_blank" 
                   style="color:#cfe8ff;"><i class="fa fa-map-marker-alt"></i> Buka Google Maps</a>
            </div>
        `,
                confirmButtonText: "Tutup",
                width: 330,
                background: "rgba(30,45,80,0.55)",
                color: "#fff"
            });
        }

        // Delete
        function confirmDelete(form) {
            event.preventDefault();
            Swal.fire({
                title: 'Hapus Mitra?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Ya, Hapus',
                cancelButtonText: 'Batal'
            }).then(x => {
                if (x.isConfirmed) form.submit();
            });
            return false;
        }

        // Live search
        function debounce(fn, delay = 250) {
            let t;
            return (...a) => {
                clearTimeout(t);
                t = setTimeout(() => fn(...a), delay);
            }
        }
        const input = document.getElementById("searchInput");
        const list = document.getElementById("list");

        async function doLiveSearch() {
            const q = input.value.trim();
            if (q === "") {
                location.href = "kontak.php";
                return;
            }

            const res = await fetch("kontak_fetch.php?q=" + encodeURIComponent(q));
            const data = await res.json();
            list.innerHTML = "";

            if (data.length === 0) {
                list.innerHTML = "<div class='empty'>Tidak ada hasil.</div>";
                return;
            }

            data.forEach(row => {
                const foto = row.foto ? `foto_mitra/${row.foto}` : "https://via.placeholder.com/300x300?text=No+Image";
                const wa = row.whatsapp.replace(/\D+/g, '');

                list.insertAdjacentHTML("beforeend", `
            <div class="contact-card">
                <div class="contact-photo"><img src="${foto}"></div>

                <div class="contact-info">
                    <div class="contact-name"
                         onclick="showDetail('${row.nama_mitra}','${row.whatsapp}','${row.alamat}','${row.maps_url}')">
                         ${row.nama_mitra}
                    </div>

                    <a class="wa-bubble-new" href="https://wa.me/${wa}" target="_blank">
                        <i class="fa fa-phone"></i> ${row.whatsapp}
                    </a>

                    <a class="map-link-new" target="_blank" href="${row.maps_url}">
                        <i class="fa fa-map-marker-alt"></i> Buka Google Maps
                    </a>
                </div>

                <?php if ($isAdmin): ?>
                <div class="contact-actions">
                    <button class="btn-edit-new" onclick="location.href='edit_mitra.php?id=${row.id}'"><i class="fa fa-pen"></i> Edit</button>

                    <form method="post" action="hapus_mitra.php" onsubmit="return confirmDelete(this)">
                        <input type="hidden" name="id" value="${row.id}">
                        <button type="submit" class="btn-delete-new"><i class="fa fa-trash"></i> Hapus</button>
                    </form>
                </div>
                <?php endif; ?>
            </div>
        `);
            });
        }
        input.addEventListener("input", debounce(doLiveSearch, 300));
    </script>

    <?php include 'navbar3.php'; ?>
</body>

</html>