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

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

// =============================
// FUNGSI UPLOAD (AMAN + GD OPSIONAL)
// =============================
function process_upload($file)
{
    if (!$file || $file['error'] !== UPLOAD_ERR_OK) return null;

    $allowed = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'];
    if (!in_array($file['type'], $allowed)) return null;

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

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

    $tmp = $file['tmp_name'];

    // Jika GD tidak aktif → simpan langsung
    if (!extension_loaded('gd')) {
        move_uploaded_file($tmp, $dir . $name);
        return $name;
    }

    // Ambil ukuran
    $info = @getimagesize($tmp);
    if (!$info) {
        move_uploaded_file($tmp, $dir . $name);
        return $name;
    }

    list($w, $h) = $info;
    $max = 800; // lebih ringan tapi masih tajam
    $ratio = min($max / $w, $max / $h, 1);

    $nw = (int)($w * $ratio);
    $nh = (int)($h * $ratio);

    if (!function_exists('imagecreatetruecolor')) {
        move_uploaded_file($tmp, $dir . $name);
        return $name;
    }

    $dst = imagecreatetruecolor($nw, $nh);
    $mime = $file['type'];

    if ($mime === 'image/png') {
        $src = imagecreatefrompng($tmp);
        imagealphablending($dst, false);
        imagesavealpha($dst, true);
    } elseif ($mime === 'image/webp') {
        $src = imagecreatefromwebp($tmp);
    } else {
        $src = imagecreatefromjpeg($tmp);
    }

    imagecopyresampled($dst, $src, 0, 0, 0, 0, $nw, $nh, $w, $h);

    $out = $dir . $name;

    if ($mime === 'image/png') {
        imagepng($dst, $out, 8); // compress sedikit lebih tinggi
    } elseif ($mime === 'image/webp') {
        imagewebp($dst, $out, 70); // lebih kecil ukurannya
    } else {
        imagejpeg($dst, $out, 75); // kualitas bagus, file kecil
    }


    imagedestroy($dst);
    imagedestroy($src);

    return $name;
}


// =============================
// PROSES SIMPAN
// =============================
$errors = [];

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

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

    if ($nama_mitra === '' || $whatsapp === '' || $alamat === '') {
        $errors[] = "Nama Mitra, WhatsApp dan Alamat wajib diisi.";
    }

    // Sanitasi WhatsApp
    $whatsapp = preg_replace('/[^\d\+]/', '', $whatsapp);

    if ($maps === '') {
        $maps = 'https://www.google.com/maps/search/?api=1&query=' . urlencode($alamat);
    }

    if (empty($errors)) {

        $foto_name = process_upload($_FILES['foto'] ?? null);

        $stmt = $koneksi->prepare("
            INSERT INTO kontak_mitra (nama_mitra, foto, whatsapp, alamat, maps_url)
            VALUES (?, ?, ?, ?, ?)
        ");

        $stmt->bind_param("sssss", $nama_mitra, $foto_name, $whatsapp, $alamat, $maps);

        if ($stmt->execute()) {
            $stmt->close();
            header("Location: kontak.php?msg=edited");
            exit;
        } else {
            $errors[] = "Gagal menyimpan data: " . $koneksi->error;
        }
    }
}
?>
<!doctype html>
<html lang="id">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Tambah 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">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

    <style>
        /* ============================================================
   GUNAKAN VARIABEL DARI CSS UTAMA KAMU
============================================================ */
        :root {
            --bg-navy: #071733;
            --card-blue: #1f4f82;
            --card-inner: #163e6b;
            --yellow: #ffd800;
            --muted: #eef3f7;
        }

        /* ============================================================
   GLOBAL
============================================================ */
        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;
            /* card luas */
            margin: 0 auto;
        }

        /* ============================================================
   CARD (SAMA STYLE DENGAN .mitra-box)
============================================================ */
        .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);
        }

        /* ============================================================
   TITLE
============================================================ */
        h2 {
            margin: 0 0 18px 0;
            color: var(--yellow);
            font-weight: 700;
            letter-spacing: .5px;
            text-align: center;

        }

        /* ============================================================
   FIELD & LABEL
============================================================ */
        .field {
            margin-bottom: 12px !important;
        }

        label {
            display: block;
            margin-bottom: 8px !important;
            color: #ffe9a3;
            font-size: 14px;
            font-weight: 600;
            padding-left: 15px;
            letter-spacing: .3px;
        }

        /* ============================================================
   INPUT & TEXTAREA (GLASS NAVY)
============================================================ */
        /* ==============================
   INPUT FINAL — Dijamin rapi
============================== */
        .input,
        textarea,
        input[type="file"] {

            width: 100%;
            padding: 14px 18px;

            margin: 0 auto;
            /* otomatis center */
            display: block;

            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;
            outline: none;
            box-sizing: border-box;

            max-width: 95%;
            /* jarak kiri-kanan aman */
        }

        /* ============================================================
   BUTTON GOLD PREMIUM (SAMA DENGAN .mitra-btn)
============================================================ */
        .btn {
            background: linear-gradient(#ffe680, #ffcc00);
            border-radius: 14px;
            padding: 12px 16px;
            border: none;
            font-weight: 700;
            font-size: 15px;
            color: #3a3300;

            box-shadow:
                0 6px 0 #d1a700,
                0 4px 10px rgba(0, 0, 0, 0.18),
                inset 0 2px 4px rgba(255, 255, 255, 0.45);

            transition:
                transform 200ms cubic-bezier(.15, .85, .35, 1),
                box-shadow 200ms ease;
        }

        .btn:hover {
            transform: translateY(-3px);
            box-shadow:
                0 8px 0 #d1a700,
                0 6px 14px rgba(0, 0, 0, 0.24),
                inset 0 2px 5px rgba(255, 255, 255, 0.55);
        }

        .btn:active {
            transform: translateY(2px);
            box-shadow:
                0 3px 0 #d1a700,
                0 3px 6px rgba(0, 0, 0, 0.22),
                inset 0 4px 6px rgba(0, 0, 0, 0.25);
        }

        /* ============================================================
   BUTTON BATAL (GLASS HITAM)
============================================================ */
        .btn-cancel {
            background: rgba(20, 20, 20, 0.45);
            border: 1.4px solid rgba(255, 255, 255, 0.25);
            padding: 12px 16px;
            border-radius: 12px;
            color: #fff;
            text-decoration: none;

            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);

            transition: transform .2s ease, box-shadow .2s ease;
        }

        .btn-cancel:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.35);
        }

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

        /* ============================================================
   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);
        }

        .foto-preview-box {
            width: 100%;
            display: flex;
            justify-content: center;
            margin-top: 12px;
        }

        /* Kotak preview 1:1 */
        #fotoPreview {
            width: 90%;
            /* ukuran bisa disesuaikan */
            max-width: 320px;
            /* batas maksimal */
            aspect-ratio: 1 / 1;
            /* <-- KUNCI agar 1:1 */

            object-fit: cover;
            /* crop otomatis */
            object-position: center;

            display: block;
            margin: 0 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);
        }


        .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;
        }

        .btn-common {
            border-radius: 14px;
            padding: 12px 16px;
            font-weight: 700;
            font-size: 15px;
            border: none;
            cursor: pointer;
            width: fit-content;
            /* tambah ini */
            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 cubic-bezier(.15, .85, .35, 1),
                box-shadow .2s ease;
        }

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

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

        /* Khusus SIMPAN = GOLD */
        .btn-save {
            background: linear-gradient(#ffe680, #ffcc00);
            color: #3a3300;
        }

        /* Khusus BATAL = GLASS NAVY */
        .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);
        }

        .btn-delete-preview {
            padding: 8px 18px;
            font-size: 13px;
            border-radius: 10px;
            border: 1.3px solid rgba(255, 255, 255, 0.3);

            background: rgba(40, 60, 110, 0.45);
            color: #fff;

            backdrop-filter: blur(8px);
            -webkit-backdrop-filter: blur(8px);

            cursor: pointer;

            /* Perbaikan di sini */
            width: fit-content;
            margin: 0 auto;

            box-shadow:
                0 4px 10px rgba(0, 0, 0, 0.25),
                inset 0 2px 4px rgba(255, 255, 255, 0.28);

            transition: 0.25s ease;
        }


        .btn-delete-preview:hover {
            transform: translateY(-2px);
            box-shadow:
                0 6px 14px rgba(0, 0, 0, 0.28),
                inset 0 2px 5px rgba(255, 255, 255, 0.32);
        }

        .btn-delete-preview:active {
            transform: translateY(2px);
            box-shadow:
                0 2px 6px rgba(0, 0, 0, 0.2),
                inset 0 3px 5px rgba(0, 0, 0, 0.25);
        }

        /* 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>Tambah Kontak 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" autocomplete="off">

                <div class="field">
                    <label>Nama Mitra</label>
                    <input class="input" name="nama_mitra"
                        autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"
                        value="<?= htmlspecialchars($_POST['nama_mitra'] ?? '') ?>">
                </div>

                <div class="field">
                    <label>Foto Toko (opsional)</label>
                    <input type="file" name="foto" accept="image/*"
                        autocomplete="off"
                        onchange="previewFoto(this)">
                </div>

                <div class="foto-preview-box" style="flex-direction: column; gap: 8px;">
                    <img id="fotoPreview" style="display:none;" />
                    <button type="button" id="hapusPreview" class="btn-delete-preview" style="display:none;">
                        Hapus Foto
                    </button>
                </div>

                <div class="field">
                    <label>Nomor WhatsApp</label>
                    <input class="input" name="whatsapp"
                        autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"
                        value="<?= htmlspecialchars($_POST['whatsapp'] ?? '') ?>">
                </div>

                <div class="field">
                    <label>Alamat</label>
                    <textarea class="input" rows="2" name="alamat"
                        autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"><?= htmlspecialchars($_POST['alamat'] ?? '') ?></textarea>
                </div>

                <div class="field">
                    <label>Google Maps URL (opsional)</label>
                    <input class="input" name="maps_url"
                        autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"
                        value="<?= htmlspecialchars($_POST['maps_url'] ?? '') ?>">
                </div>

                <div style="display:flex;justify-content:center;gap:14px;margin-top:18px;">
                    <button class="btn-common btn-save" type="button" id="btnSimpan">Simpan</button>
                    <a href="#" class="btn-common btn-cancel-new" id="btnBatal"
                        style="text-decoration:none;display:flex;align-items:center;justify-content:center;">
                        Batal
                    </a>

                </div>

            </form>

        </div>
    </div>
    <script>
        function previewFoto(input) {
            const preview = document.getElementById('fotoPreview');
            const btnHapus = document.getElementById('hapusPreview');

            if (input.files && input.files[0]) {
                preview.style.display = "block";
                preview.src = URL.createObjectURL(input.files[0]);
                btnHapus.style.display = "inline-block"; // tampilkan tombol hapus
            }
        }

        document.getElementById('hapusPreview').addEventListener('click', function() {
            const preview = document.getElementById('fotoPreview');
            const inputFile = document.querySelector('input[name="foto"]');

            preview.src = "";
            preview.style.display = "none";

            this.style.display = "none"; // sembunyikan tombol hapus

            // reset file input
            inputFile.value = "";
        });
    </script>
    <script>
        document.getElementById('btnSimpan').addEventListener('click', function(e) {
            Swal.fire({
                title: 'Simpan Data?',
                text: "Pastikan data sudah benar.",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#28a745',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Ya, Simpan',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    document.querySelector('form').submit();
                }
            });
        });

        document.getElementById('btnBatal').addEventListener('click', function(e) {
            e.preventDefault();

            Swal.fire({
                title: 'Batalkan Pengisian?',
                text: "Data yang diisi akan hilang.",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Ya, Batalkan',
                cancelButtonText: 'Kembali'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = "kontak.php";
                }
            });
        });
    </script>

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

</body>

</html>