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

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: kontak.php");
    exit;
}

// pastikan $errors selalu ada
$errors = [];

if (!isset($_GET['id'])) {
    die("ID tidak ditemukan.");
}

$id = intval($_GET['id']);
$mitra = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT * FROM kontak_mitra WHERE id=$id"));

if (!$mitra) die("Data tidak ditemukan.");

function process_upload($file)
{
    if (!$file || $file['error'] !== UPLOAD_ERR_OK) return null;

    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $name = time() . "_" . bin2hex(random_bytes(5)) . "." . $ext;

    $dir = __DIR__ . "/foto_mitra/";
    if (!is_dir($dir)) mkdir($dir, 0755, true);

    move_uploaded_file($file['tmp_name'], $dir . $name);
    return $name;
}

$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $nama = trim($_POST['nama_mitra']);
    $wa   = trim($_POST['whatsapp']);
    $alamat = trim($_POST['alamat']);
    $maps   = trim($_POST['maps_url']);

    if ($nama == "" || $wa == "" || $alamat == "") {
        $errors[] = "Semua field wajib diisi.";
    }

    $foto = $mitra['foto'];

    if (!empty($_FILES['foto']['name'])) {
        $fotoBaru = process_upload($_FILES['foto']);
        if ($fotoBaru) {
            if ($foto && file_exists("foto_mitra/$foto")) unlink("foto_mitra/$foto");
            $foto = $fotoBaru;
        }
    }

    if (empty($errors)) {
        $stmt = $koneksi->prepare("
            UPDATE kontak_mitra 
            SET nama_mitra=?, whatsapp=?, alamat=?, maps_url=?, foto=? WHERE id=?
        ");
        $stmt->bind_param("sssssi", $nama, $wa, $alamat, $maps, $foto, $id);
        $stmt->execute();

        $success = true;
    }
}
?>
<!doctype html>
<html lang="id">

<head>
    <meta charset="utf-8">
    <title>Edit Mitra</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">

    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <link rel="stylesheet" href="css/navbar.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        /* ======================================
   VARIABLE SAMA DENGAN HALAMAN TAMBAH
====================================== */
        :root {
            --bg-navy: #071733;
            --card-blue: #233a6a;
            --yellow: #ffd800;
        }

        body {
            margin: 0;
            font-family: 'Segoe UI', Roboto, Arial, sans-serif;
            background: var(--bg-navy);
            color: #fff;
            padding: 10px;
            padding-bottom: 100px;
        }

        .container {
            width: 100%;
            max-width: 600px;
            margin: 0 auto;
        }

        /* CARD NAVY GLASS */
        .card {
            background: #233a6a;
            backdrop-filter: blur(14px) saturate(160%);
            -webkit-backdrop-filter: blur(14px) saturate(160%);
            border-radius: 15px;
            border: 1.5px solid rgba(255, 210, 90, 0.45);
            padding: 20px 10px 30px 10px;
            box-shadow:
                inset 0 1px 3px rgba(255, 255, 255, 0.35),
                inset 0 -2px 3px rgba(120, 80, 0, 0.20),
                0 6px 16px rgba(0, 0, 0, 0.28),
                0 0 10px rgba(255, 200, 60, 0.18);
        }

        h2 {
            color: var(--yellow);
            text-align: center;
            margin: 10px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            color: #ffe9a3;
            font-size: 14px;
            font-weight: 600;
            padding-left: 15px;
        }

        .input,
        textarea,
        input[type="file"] {
            width: 100%;
            padding: 14px 18px;
            border-radius: 14px;
            background: rgba(255, 255, 255, 0.08);
            border: 1.6px solid rgba(255, 255, 255, 0.25);
            color: #fff;
            font-size: 15px;
            box-sizing: border-box;
            margin-bottom: 14px;
        }

        .input:focus,
        textarea:focus,
        input[type="file"]:focus {
            border-color: rgba(255, 210, 90, 0.95);
            box-shadow:
                0 0 10px rgba(255, 210, 90, 0.55),
                inset 0 1px 3px rgba(255, 255, 255, 0.35);
            transition: 0.25s ease;
        }

        /* ERROR BOX */
        .err {
            background: rgba(255, 80, 80, 0.25);
            border: 1px solid rgba(255, 120, 120, 0.4);
            color: #ffeaea;
            padding: 10px 12px;
            border-radius: 10px;
            margin-bottom: 12px;
            backdrop-filter: blur(10px);
        }

        /* PREVIEW FOTO 1:1 */
        #fotoPreview {
            width: 90%;
            max-width: 320px;
            aspect-ratio: 1 / 1;
            object-fit: cover;
            object-position: center;
            display: block;
            margin: 10px auto;
            border-radius: 14px;
            border: 2px solid rgba(255, 255, 255, 0.25);
            box-shadow:
                0 3px 12px rgba(0, 0, 0, 0.35),
                inset 0 2px 3px rgba(255, 255, 255, 0.22);
        }

        /* BUTTON STYLE */
        .btn-common {
            border-radius: 14px;
            padding: 12px 16px;
            font-weight: 700;
            font-size: 15px;
            cursor: pointer;
            border: none;
            box-shadow:
                0 6px 0 rgba(0, 0, 0, 0.3),
                0 4px 10px rgba(0, 0, 0, 0.18),
                inset 0 2px 4px rgba(255, 255, 255, 0.35);
            transition: transform .2s, box-shadow .2s;
        }

        .btn-save {
            background: linear-gradient(#ffe680, #ffcc00);
            color: #3a3300;
        }

        .btn-cancel-new {
            background: rgba(80, 100, 160, 0.45);
            color: #fff;
            border: 1.4px solid rgba(255, 255, 255, 0.25);
            backdrop-filter: blur(10px);
            text-decoration: none;
        }

        .btn-common:hover {
            transform: translateY(-3px);
        }

        .btn-common:active {
            transform: translateY(2px);
        }

        /* 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">
        <h2>Edit Mitra</h2>
        <div class="card">

            <?php if (!empty($errors)): ?>
                <?php foreach ($errors as $e): ?>
                    <div class="err"><?= htmlspecialchars($e) ?></div>
                <?php endforeach; ?>
            <?php endif; ?>

            <form method="post" enctype="multipart/form-data">

                <label>Nama Mitra</label>
                <input class="input" name="nama_mitra" value="<?= htmlspecialchars($mitra['nama_mitra']) ?>">

                <label>WhatsApp</label>
                <input class="input" name="whatsapp" value="<?= htmlspecialchars($mitra['whatsapp']) ?>">

                <label>Alamat</label>
                <textarea class="input" name="alamat"><?= htmlspecialchars($mitra['alamat']) ?></textarea>

                <label>Google Maps URL</label>
                <input class="input" name="maps_url" value="<?= htmlspecialchars($mitra['maps_url']) ?>">

                <label>Foto Saat Ini</label>
                <img id="fotoPreview" src="foto_mitra/<?= $mitra['foto'] ?>">

                <label>Ganti Foto (opsional)</label>
                <input type="file" name="foto" id="inputFoto" class="input" accept="image/*">

                <div style="display:flex;justify-content:center;gap:14px;margin-top:18px;">

                    <!-- Simpan Perubahan with confirm -->
                    <button class="btn-common btn-save" type="button" id="btnSave">
                        Simpan Perubahan
                    </button>

                    <button type="button" id="btnCancel" class="btn-common btn-cancel-new">
                        Batal
                    </button>
                </div>
            </form>
        </div>
    </div>

    <?php if ($success): ?>
        <script>
            Swal.fire({
                icon: 'success',
                title: 'Berhasil!',
                text: 'Data mitra berhasil diperbarui.',
                confirmButtonColor: '#ffcc00'
            }).then(() => {
                window.location.href = "kontak.php?msg=edited";
            });
        </script>
    <?php endif; ?>

    <script>
        // === Konfirmasi SIMPAN PERUBAHAN ===
        document.getElementById('btnSave').addEventListener('click', function() {
            Swal.fire({
                title: "Yakin untuk merubah data?",
                text: "Perubahan akan disimpan ke database.",
                icon: "warning",
                showCancelButton: true,
                confirmButtonColor: "#ffcc00",
                cancelButtonColor: "#d33",
                confirmButtonText: "Ya, simpan",
                cancelButtonText: "Batal"
            }).then((result) => {
                if (result.isConfirmed) {
                    document.querySelector("form").submit();
                }
            });
        });

        // === Konfirmasi BATAL ===
        document.getElementById('btnCancel').addEventListener('click', function() {
            Swal.fire({
                icon: 'warning',
                title: 'Batalkan perubahan?',
                text: 'Perubahan yang belum disimpan akan hilang.',
                showCancelButton: true,
                confirmButtonText: 'Ya, batal',
                cancelButtonText: 'Kembali',
                confirmButtonColor: '#d33'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = "kontak.php";
                }
            });
        });
    </script>
    <script>
        // ==== PREVIEW FOTO BARU ====
        document.getElementById('inputFoto').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (!file) return;

            const reader = new FileReader();
            reader.onload = function(evt) {
                document.getElementById('fotoPreview').src = evt.target.result;
            }
            reader.readAsDataURL(file);
        });
    </script>
    <?php include 'navbar3.php'; ?>

</body>

</html>