<?php
$servername = "localhost";
$username = "meja4595_juraganfiber"; // <--- GANTI USER ANDA
$password = "gudangselatan"; // <--- GANTI PASSWORD ANDA
$dbname = "meja4595_katalogdb"; // Nama database Anda

// Membuat koneksi ke database
$conn = new mysqli($servername, $username, $password, $dbname);

// Cek koneksi
if ($conn->connect_error) {
    // Di lingkungan produksi, jangan tampilkan error detail ke pengguna
    die("Koneksi database gagal: " . $conn->connect_error);
}

// ... (Kode lainnya sama persis)

// 1. Tambah Produk Baru (CREATE)
if (isset($_POST['add_product'])) {
    // Ambil input dari form
    $sku = trim($_POST['sku']);
    $name = trim($_POST['name']);
    $category = trim($_POST['category']);
    $description = trim($_POST['description']);
    $price = (float)$_POST['price'];

    $foto_path = handle_upload($_FILES['images']);
    
    // Nilai default untuk kolom view_count dan add_to_cart
    $view_count = 0;
    $add_to_cart = 0;

    if ($foto_path) {
        $sql = "INSERT INTO products (sku, name, category, description, price, images, view_count, add_to_cart) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        
        // s: string, d: double (float), i: integer
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ssdsdsii", $sku, $name, $category, $description, $price, $foto_path, $view_count, $add_to_cart);

        try {
            if ($stmt->execute()) {
                $message = "Produk berhasil ditambahkan! (SKU: $sku)";
                $message_type = 'success';
            } else {
                // Tambahkan ini untuk melihat error jika execute gagal
                $message = "Gagal mengeksekusi query: " . $stmt->error;
                $message_type = 'error';
            }
        } catch (mysqli_sql_exception $e) {
            // Error 1062 adalah Duplikat entry (jika SKU UNIQUE)
            if ($e->getCode() == 1062) {
                $message = "Gagal: SKU '$sku' sudah ada. Silakan gunakan SKU yang berbeda.";
            } else {
                $message = "Error database: " . $e->getMessage();
                // Jika error lain, Anda akan melihat pesan yang lebih spesifik
            }
            $message_type = 'error';
        }
        $stmt->close();
    } else {
        $message = "Gagal mengunggah foto. Pastikan format file benar (JPG/PNG/GIF).";
        $message_type = 'error';
    }
}

// 2. Edit Produk (UPDATE)
if (isset($_POST['edit_product'])) {
    $id = (int)$_POST['id_produk'];
    $sku = trim($_POST['sku']);
    $name = trim($_POST['name']);
    $category = trim($_POST['category']);
    $description = trim($_POST['description']);
    $price = (float)$_POST['price'];
    $new_foto_path = null;

    // Cek apakah ada file foto baru yang diupload
    if (isset($_FILES['images']) && $_FILES['images']['error'] == 0) {
        $new_foto_path = handle_upload($_FILES['images']);
    }

    try {
        if ($new_foto_path) {
            // Hapus foto lama sebelum update
            $res = $conn->query("SELECT images FROM products WHERE id = $id");
            $row = $res->fetch_assoc();
            $old_foto = $row['images'] ?? null;
            if ($old_foto && file_exists($target_dir . $old_foto)) {
                unlink($target_dir . $old_foto);
            }
            
            // Update dengan foto baru
            $sql = "UPDATE products SET sku=?, name=?, category=?, description=?, price=?, images=? WHERE id=?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ssdsdsi", $sku, $name, $category, $description, $price, $new_foto_path, $id);
        } else {
            // Update tanpa mengubah foto
            $sql = "UPDATE products SET sku=?, name=?, category=?, description=?, price=? WHERE id=?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ssdsdi", $sku, $name, $category, $description, $price, $id);
        }

        if ($stmt->execute()) {
            $message = "Produk berhasil diperbarui! (ID: $id)";
            $message_type = 'success';
        } else {
            $message = "Gagal memperbarui produk: " . $stmt->error;
            $message_type = 'error';
        }
        $stmt->close();
    } catch (mysqli_sql_exception $e) {
        $message = "Error database saat update: " . $e->getMessage();
        $message_type = 'error';
    }
}

// 3. Hapus Produk (DELETE)
if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $delete_success = false;
    
    // Ambil nama file foto sebelum dihapus dari DB
    $res = $conn->query("SELECT images FROM products WHERE id = $id");
    $row = $res->fetch_assoc();
    $old_foto = $row['images'] ?? null;
    
    // Gunakan Prepared Statement untuk menghapus
    $sql = "DELETE FROM products WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $id);

    if ($stmt->execute()) {
        $delete_success = true;
        // Hapus file foto dari server
        if ($old_foto && file_exists($target_dir . $old_foto)) {
            unlink($target_dir . $old_foto);
        }
        $message = "Produk berhasil dihapus!";
        $message_type = 'success';
    } else {
        $message = "Error: " . $stmt->error;
        $message_type = 'error';
    }
    $stmt->close();
    
    // Redirect untuk menghindari re-submission form
    header('Location: kelolaproduk.php?msg_type=' . $message_type . '&msg=' . urlencode($message));
    exit();
}

// 4. Baca Semua Produk (READ)
$products = [];
// Select semua kolom sesuai skema DB Anda
$sql = "SELECT id, sku, name, category, description, price, images, view_count, add_to_cart FROM products ORDER BY id DESC";
$result = $conn->query($sql);

if ($result && $result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $products[] = $row;
    }
}

// Ambil pesan dari URL redirect jika ada (setelah delete/tambah/edit)
if (isset($_GET['msg']) && isset($_GET['msg_type'])) {
    $message = urldecode($_GET['msg']);
    $message_type = $_GET['msg_type'];
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola Produk - Dasbor Admin (meja4595)</title>
    <!-- Anda bisa menautkan file CSS eksternal di sini: dashboard.css -->
    <style>
        /* CSS Khusus untuk Halaman Kelola Produk */
        body { font-family: 'Arial', sans-serif; background-color: #f4f7f6; margin: 0; padding: 0; }
        #dashboard-content { max-width: 1200px; margin: 20px auto; background: white; border-radius: 10px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
        .dashboard-header { padding: 20px; border-bottom: 1px solid #eee; display: flex; justify-content: space-between; align-items: center; }
        .dashboard-header h1 { margin: 0; color: #007bff; }
        .product-manager { padding: 20px; }
        .product-manager h2 { margin-bottom: 20px; color: #333; border-left: 5px solid #007bff; padding-left: 10px; }
        
        /* Nav Tabs */
        .tabs { display: flex; border-bottom: 2px solid #ddd; padding: 0 20px; }
        .tab-link { padding: 10px 15px; text-decoration: none; color: #666; font-weight: bold; border-radius: 5px 5px 0 0; transition: background-color 0.3s; }
        .tab-link:hover { background-color: #f0f0f0; }
        .tab-link.active { background-color: white; border: 2px solid #ddd; border-bottom: none; color: #007bff; }

        /* Tabel Produk */
        .product-table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        .product-table th, .product-table td { border: 1px solid #eee; padding: 12px; text-align: left; vertical-align: middle; }
        .product-table th { background-color: #007bff; color: white; font-weight: 600; font-size: 0.8rem; }
        .product-table tr:nth-child(even) { background-color: #f9f9f9; }
        .product-table img { width: 50px; height: 50px; object-fit: cover; border-radius: 4px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
        
        /* Tombol Aksi */
        .action-buttons button, .add-product-btn { 
            padding: 8px 12px; border: none; cursor: pointer; border-radius: 4px; font-weight: bold; transition: background-color 0.3s, transform 0.1s;
        }
        .action-buttons .edit-btn { background-color: #ffc107; color: #333; }
        .action-buttons .delete-btn { background-color: #dc3545; color: white; }
        .action-buttons button:hover, .add-product-btn:hover { transform: translateY(-1px); opacity: 0.9; }

        .add-product-btn { background-color: #28a745; color: white; margin-bottom: 20px; }
        .add-product-btn[style*="#6c757d"] { background-color: #6c757d !important; } /* Tombol kembali */

        /* Modal Styles */
        .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.6); padding-top: 60px; }
        .modal-content { background-color: #fefefe; margin: 5% auto; padding: 30px; border-radius: 10px; width: 90%; max-width: 600px; box-shadow: 0 8px 25px rgba(0,0,0,0.5); }
        .close-btn { color: #aaa; float: right; font-size: 28px; font-weight: bold; }
        .close-btn:hover, .close-btn:focus { color: #000; text-decoration: none; cursor: pointer; }
        
        .form-group label { display: block; margin-bottom: 5px; font-weight: bold; color: #555; }
        .form-group input[type="text"], .form-group input[type="number"], .form-group textarea {
            width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 6px; box-sizing: border-box; margin-top: 4px;
        }
        .alert { padding: 15px; margin-bottom: 20px; border-radius: 4px; color: white; font-weight: bold; }
        .alert.success { background-color: #28a745; }
        .alert.error { background-color: #dc3545; }
    </style>
</head>
<body>
    <div id="dashboard-content">  
        <header class="dashboard-header">
            <h1>Kelola Produk Katalog (Database: meja4595_katalogdb)</h1>
            <a href="dashboard.html" class="add-product-btn" style="background-color: #6c757d;">Kembali ke Dasbor</a>
        </header>

        <nav class="tabs">
            <a href="dashboard.html?tab=orders" class="tab-link">Daftar Pesanan</a>
            <a href="dashboard.html?tab=analytics" class="tab-link">Analitik Produk</a>
            <a href="kelolaproduk.php" class="tab-link active">Kelola Produk</a>
        </nav>

        <main class="main-content product-manager">
            <?php if ($message): ?>
                <div class="alert <?php echo $message_type; ?>">
                    <?php echo htmlspecialchars($message); ?>
                </div>
            <?php endif; ?>

            <button class="add-product-btn" id="openAddModal">Tambah Produk Baru</button>

            <h2>Daftar Semua Produk (<?php echo count($products); ?>)</h2>
            
            <div style="overflow-x:auto;">
                <table class="product-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Foto (images)</th>
                            <th>SKU</th>
                            <th>Nama Produk (name)</th>
                            <th>Kategori (category)</th>
                            <th>Harga (price)</th>
                            <th>View Count</th>
                            <th>Add to Cart</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($products)): ?>
                            <tr>
                                <td colspan="9" style="text-align: center;">Belum ada produk yang ditambahkan.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($products as $product): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($product['id']); ?></td>
                                    <td>
                                        <?php 
                                            $foto_url = $target_dir . htmlspecialchars($product['images']);
                                            $placeholder = 'https://placehold.co/50x50/cccccc/333333?text=N/A';
                                        ?>
                                        <img src="<?php echo $product['images'] ? $foto_url : $placeholder; ?>" 
                                            alt="<?php echo htmlspecialchars($product['name']); ?>" 
                                            onerror="this.onerror=null;this.src='<?php echo $placeholder; ?>';"
                                        >
                                    </td>
                                    <td><?php echo htmlspecialchars($product['sku']); ?></td>
                                    <td><?php echo htmlspecialchars($product['name']); ?></td>
                                    <td><?php echo htmlspecialchars($product['category']); ?></td>
                                    <td>Rp <?php echo number_format($product['price'], 0, ',', '.'); ?></td>
                                    <td><?php echo number_format($product['view_count'], 0, ',', '.'); ?></td>
                                    <td><?php echo number_format($product['add_to_cart'], 0, ',', '.'); ?></td>
                                    <td class="action-buttons">
                                        <button class="edit-btn" 
                                                    onclick="openEditModal(
                                                        <?php echo $product['id']; ?>, 
                                                        '<?php echo htmlspecialchars($product['sku']); ?>',
                                                        '<?php echo htmlspecialchars($product['name']); ?>', 
                                                        '<?php echo htmlspecialchars($product['category']); ?>', 
                                                        '<?php echo htmlspecialchars(str_replace(["\r", "\n"], ' ', $product['description'])); ?>', 
                                                        <?php echo $product['price']; ?>,
                                                        '<?php echo htmlspecialchars($product['images'] ? $foto_url : $placeholder); ?>'
                                                    )">Edit</button>
                                        <button class="delete-btn" 
                                                    onclick="confirmDelete(<?php echo $product['id']; ?>, '<?php echo htmlspecialchars($product['name']); ?>')">Hapus</button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </main>
    </div>

    <!-- Modal Tambah Produk Baru -->
    <div id="addProductModal" class="modal">
        <div class="modal-content">
            <span class="close-btn" onclick="closeModal('addProductModal')">&times;</span>
            <h3>Tambah Produk Baru</h3>
            <form action="kelolaproduk.php" method="POST" enctype="multipart/form-data">
                <div class="form-group">
                    <label for="add_sku">SKU (Stock Keeping Unit):</label>
                    <input type="text" id="add_sku" name="sku" required maxlength="255">
                </div>
                <div class="form-group">
                    <label for="add_name">Nama Produk (name):</label>
                    <input type="text" id="add_name" name="name" required maxlength="255">
                </div>
                <div class="form-group">
                    <label for="add_category">Kategori (category):</label>
                    <input type="text" id="add_category" name="category" required maxlength="255">
                </div>
                <div class="form-group">
                    <label for="add_description">Deskripsi (description):</label>
                    <textarea id="add_description" name="description" rows="4" required></textarea>
                </div>
                <div class="form-group">
                    <label for="add_price">Harga (price - Rp):</label>
                    <input type="number" step="0.01" id="add_price" name="price" required min="0">
                </div>
                <div class="form-group">
                    <label for="add_images">Foto Utama (images):</label>
                    <input type="file" id="add_images" name="images" accept="image/*" required>
                </div>
                <button type="submit" name="add_product" class="add-product-btn">Simpan Produk</button>
            </form>
        </div>
    </div>

    <!-- Modal Edit Produk -->
    <div id="editProductModal" class="modal">
        <div class="modal-content">
            <span class="close-btn" onclick="closeModal('editProductModal')">&times;</span>
            <h3>Edit Produk</h3>
            <form action="kelolaproduk.php" method="POST" enctype="multipart/form-data">
                <input type="hidden" id="edit_id" name="id_produk">
                <div class="form-group">
                    <label for="edit_sku">SKU (Stock Keeping Unit):</label>
                    <input type="text" id="edit_sku" name="sku" required maxlength="255">
                </div>
                <div class="form-group">
                    <label for="edit_name">Nama Produk (name):</label>
                    <input type="text" id="edit_name" name="name" required maxlength="255">
                </div>
                <div class="form-group">
                    <label for="edit_category">Kategori (category):</label>
                    <input type="text" id="edit_category" name="category" required maxlength="255">
                </div>
                <div class="form-group">
                    <label for="edit_description">Deskripsi (description):</label>
                    <textarea id="edit_description" name="description" rows="4" required></textarea>
                </div>
                <div class="form-group">
                    <label for="edit_price">Harga (price - Rp):</label>
                    <input type="number" step="0.01" id="edit_price" name="price" required min="0">
                </div>
                <!-- Kolom view_count dan add_to_cart tidak diubah manual, hanya price -->
                <div class="form-group">
                    <label for="edit_images">Ganti Foto Utama (images):</label>
                    <input type="file" id="edit_images" name="images" accept="image/*">
                    <div class="current-foto">
                        <p>Foto Saat Ini:</p>
                        <img id="current_foto_preview" src="" alt="Foto Produk Saat Ini" style="width: 100px; height: 100px; object-fit: cover; border-radius: 4px;">
                    </div>
                </div>
                <button type="submit" name="edit_product" class="add-product-btn">Update Produk</button>
            </form>
        </div>
    </div>

    <!-- JavaScript untuk Interaksi UI -->
    <script>
        const addModal = document.getElementById('addProductModal');
        const editModal = document.getElementById('editProductModal');

        // Fungsi buka/tutup modal
        document.getElementById('openAddModal').addEventListener('click', () => {
            addModal.style.display = 'block';
        });

        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }

        window.onclick = function(event) {
            if (event.target == addModal) {
                addModal.style.display = 'none';
            }
            if (event.target == editModal) {
                editModal.style.display = 'none';
            }
        }

        /**
         * Fungsi Buka Modal Edit dengan data yang sinkron dengan kolom DB.
         * Parameter: id, sku, name, category, description, price, imagesUrl
         */
        function openEditModal(id, sku, name, category, description, price, imagesUrl) {
            document.getElementById('edit_id').value = id;
            document.getElementById('edit_sku').value = sku;
            document.getElementById('edit_name').value = name;
            document.getElementById('edit_category').value = category;
            
            // Mengganti karakter spasi ganda yang digunakan saat encoding deskripsi menjadi baris baru
            const cleanDescription = description.replace(/ {2}/g, '\n');
            document.getElementById('edit_description').value = cleanDescription;

            document.getElementById('edit_price').value = price;
            document.getElementById('current_foto_preview').src = imagesUrl;

            editModal.style.display = 'block';
        }

        // Fungsi Konfirmasi Hapus
        function confirmDelete(id, name) {
            if (window.confirm(`Yakin ingin menghapus produk "${name}" (ID: ${id})? Data akan hilang permanen.`)) {
                // Redirect ke PHP untuk pemrosesan hapus
                window.location.href = `kelolaproduk.php?action=delete&id=${id}`;
            }
        }
    </script>
</body>
</html>
