<?php
session_start();

include 'db.php';

if ($_SESSION['username'] !== "admin@admin.com") {
    header("Location: login.php");
    exit;
}

$message = "";
$success = false;
$nama_toko_lama = "";
$logo_lama = "";

/* -----------------------------------------
   1. Ambil data logo toko yang sedang aktif
------------------------------------------*/
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
    die("Koneksi gagal: " . $conn->connect_error);
}

$result = $conn->query("SELECT Nama_toko, Gambar_logo FROM logo LIMIT 1");
if ($result && $row = $result->fetch_assoc()) {
    $nama_toko_lama = $row['Nama_toko'];
    $logo_lama = $row['Gambar_logo'];
}
$conn->close();

/* -----------------------------------------
   2. Proses form jika ada kiriman POST
------------------------------------------*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nama_toko = trim($_POST['nama_toko'] ?? '');
    $target_dir = "gambar/";

    if (!is_dir($target_dir)) {
        mkdir($target_dir, 0777, true);
    }

    $nama_file = basename($_FILES["logo_toko"]["name"] ?? '');
    $target_file = $target_dir . $nama_file;
    $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
    $uploadOk = 1;

    if (!empty($_FILES["logo_toko"]["tmp_name"])) {
        $check = getimagesize($_FILES["logo_toko"]["tmp_name"]);
        if ($check === false) {
            $message .= "❌ File bukan gambar.<br>";
            $uploadOk = 0;
        }

        if (file_exists($target_file)) {
            $message .= "⚠️ File sudah ada, ganti nama file sebelum upload.<br>";
            $uploadOk = 0;
        }

        if ($_FILES["logo_toko"]["size"] > 5000000) {
            $message .= "❌ Ukuran file terlalu besar (maks 5MB).<br>";
            $uploadOk = 0;
        }

        if (!in_array($imageFileType, ["jpg", "jpeg", "png", "gif"])) {
            $message .= "❌ Hanya file JPG, JPEG, PNG & GIF yang diizinkan.<br>";
            $uploadOk = 0;
        }

        if ($uploadOk == 1) {
            if (move_uploaded_file($_FILES["logo_toko"]["tmp_name"], $target_file)) {
                $message .= "✅ File <b>" . htmlspecialchars($nama_file) . "</b> berhasil diupload.<br>";

                // Simpan ke database
                $conn = new mysqli($servername, $username, $password, $database);
                if ($conn->connect_error) {
                    die("Koneksi gagal: " . $conn->connect_error);
                }

                $stmt = $conn->prepare("UPDATE logo SET Nama_toko = ?, Gambar_logo = ? WHERE 1");
                $stmt->bind_param("ss", $nama_toko, $nama_file);

                if ($stmt->execute()) {
                    $message .= "✅ <b>Data Toko berhasil disimpan.</b>";
                    $success = true;
                    $nama_toko_lama = $nama_toko;
                    $logo_lama = $nama_file;
                } else {
                    $message .= "❌ Gagal menyimpan data: " . htmlspecialchars($stmt->error);
                }

                $stmt->close();
                $conn->close();
            } else {
                $message .= "❌ Gagal mengupload file.<br>";
            }
        }
    } else {
        $message .= "⚠️ Tidak ada file yang diupload.<br>";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Pengaturan Logo Toko</title>
    <style>
        body {
            font-family: Verdana, sans-serif;
            background-color: #f2f2f2;
        }
        .container {
            margin: 50px auto;
            width: 600px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 10px #ccc;
            padding: 30px;
        }
        h2 {
            text-align: center;
            color: #333;
        }
        .message {
            background: #fff3cd;
            border: 1px solid #ffeeba;
            padding: 10px;
            margin-bottom: 20px;
            border-radius: 6px;
            color: #856404;
        }
        table {
            width: 100%;
            font-size: 14px;
        }
        td {
            padding: 8px;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 10px 25px;
            border-radius: 5px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        .preview {
            text-align: center;
            margin-top: 15px;
        }
        .preview img {
            max-width: 200px;
            border-radius: 10px;
            box-shadow: 0 0 5px #999;
        }
        .old-logo {
            text-align: center;
            margin-bottom: 30px;
            padding: 15px;
            background: #fafafa;
            border-radius: 8px;
            border: 1px solid #eee;
        }
        .old-logo h4 {
            color: #444;
        }
    </style>
</head>
<body>

<div class="container">
    <h2>🛒 Pengaturan Logo Toko</h2>

    <?php if (!empty($nama_toko_lama)): ?>
        <div class="old-logo">
            <h4>🧾 Logo Toko Saat Ini</h4>
            <p><b>Nama Toko:</b> <?= htmlspecialchars($nama_toko_lama) ?></p>
            <?php if (!empty($logo_lama)): ?>
                <img src="gambar/<?= htmlspecialchars($logo_lama) ?>" alt="Logo Lama" width="150">
            <?php else: ?>
                <p><i>(Belum ada logo)</i></p>
            <?php endif; ?>
        </div>
    <?php endif; ?>

    <?php if (!empty($message)): ?>
        <div class="message"><?= $message ?></div>
    <?php endif; ?>

    <form method="post" enctype="multipart/form-data">
        <table>
            <tr>
                <td>Nama Toko</td>
                <td><input type="text" name="nama_toko" size="40" required value="<?= htmlspecialchars($nama_toko_lama) ?>"></td>
            </tr>
            <tr>
                <td>Logo Toko</td>
                <td><input type="file" name="logo_toko" accept="image/*" required></td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <button type="submit" onclick="this.disabled=true; this.form.submit();">Simpan</button>
                </td>
            </tr>
        </table>
    </form>

    <?php if ($success): ?>
        <div class="preview">
            <h4>✅ Logo Baru:</h4>
            <img src="gambar/<?= htmlspecialchars($logo_lama) ?>" alt="Logo Baru" width=150>
        </div>
    <?php endif; ?>
</div>

</body>
</html>
