<?php
$admin_title = "Tambah Produk";
require_once 'includes/header.php';

$error = '';
$success = '';

$categories = [];
try {
    $stmt = $pdo->query("SELECT * FROM categories ORDER BY name ASC");
    $categories = $stmt->fetchAll();
} catch (Exception $e) {
    $error = "Gagal memuat kategori: " . $e->getMessage();
}

if (isset($_POST['add_product'])) {
    $name = trim($_POST['name']);
    $category = trim($_POST['category']);
    $description = trim($_POST['description']);
    $size_available = trim($_POST['size_available']);
    $finishing = trim($_POST['finishing']);
    $is_featured = isset($_POST['is_featured']) ? 1 : 0;
    
    // Image Handling
    $image_name = '';
    
    if (empty($name) || empty($category)) {
        $error = "Nama produk dan Kategori wajib diisi.";
    } else {
        if (isset($_FILES['image']) && $_FILES['image']['error'] == UPLOAD_ERR_OK) {
            $file_tmp = $_FILES['image']['tmp_name'];
            $file_name = $_FILES['image']['name'];
            $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
            
            $allowed_exts = ['jpg', 'jpeg', 'png', 'webp'];
            
            if (in_array($file_ext, $allowed_exts)) {
                $new_file_name = uniqid('prod_', true) . '.' . $file_ext;
                $dest_dir = __DIR__ . '/../uploads/';
                
                if (!is_dir($dest_dir)) {
                    mkdir($dest_dir, 0777, true);
                }
                
                if (move_uploaded_file($file_tmp, $dest_dir . $new_file_name)) {
                    $image_name = $new_file_name;
                } else {
                    $error = "Gagal memindahkan file gambar yang diunggah.";
                }
            } else {
                $error = "Format file tidak didukung. Harap unggah format JPG, JPEG, PNG, atau WEBP.";
            }
        }
        
        if (empty($error)) {
            try {
                $stmt = $pdo->prepare("INSERT INTO products (name, category, description, size_available, finishing, image, is_featured) VALUES (?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$name, $category, $description, $size_available, $finishing, $image_name, $is_featured]);
                
                $success = "Produk baru berhasil ditambahkan!";
                // Clear inputs
                $_POST = array();
            } catch (Exception $e) {
                $error = "Gagal menyimpan ke database: " . $e->getMessage();
            }
        }
    }
}
?>

<?php if (!empty($error)): ?>
    <div style="background-color: rgba(239, 68, 68, 0.15); border: 1px solid var(--error); color: #f87171; padding: 12px 15px; border-radius: 6px; font-size: 13px; margin-bottom: 20px;">
        <i class="fas fa-exclamation-circle" style="margin-right: 5px;"></i> <?php echo $error; ?>
    </div>
<?php endif; ?>

<?php if (!empty($success)): ?>
    <div style="background-color: rgba(16, 185, 129, 0.15); border: 1px solid var(--success); color: #34d399; padding: 12px 15px; border-radius: 6px; font-size: 13px; margin-bottom: 20px;">
        <i class="fas fa-check-circle" style="margin-right: 5px;"></i> <?php echo $success; ?>
    </div>
<?php endif; ?>

<div class="form-card">
    <form action="" method="POST" enctype="multipart/form-data">
        <div class="form-row">
            <div class="form-group">
                <label for="name">Nama Produk *</label>
                <input type="text" id="name" name="name" class="form-control" placeholder="Contoh: Batu Andesit Bakar" required value="<?php echo isset($_POST['name']) ? htmlspecialchars($_POST['name']) : ''; ?>">
            </div>
            
            <div class="form-group">
                <label for="category">Kategori *</label>
                <select id="category" name="category" class="form-control" required>
                    <option value="">-- Pilih Kategori --</option>
                    <?php foreach ($categories as $cat): ?>
                        <option value="<?php echo htmlspecialchars($cat['name']); ?>" <?php echo (isset($_POST['category']) && $_POST['category'] == $cat['name']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($cat['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
        
        <div class="form-row">
            <div class="form-group">
                <label for="finishing">Finishing Tersedia</label>
                <input type="text" id="finishing" name="finishing" class="form-control" placeholder="Contoh: Bakar (Flamed), Polished, RTM" value="<?php echo isset($_POST['finishing']) ? htmlspecialchars($_POST['finishing']) : ''; ?>">
            </div>
            
            <div class="form-group">
                <label for="size_available">Ukuran Tersedia</label>
                <input type="text" id="size_available" name="size_available" class="form-control" placeholder="Contoh: 30x30 cm, 30x60 cm, Custom" value="<?php echo isset($_POST['size_available']) ? htmlspecialchars($_POST['size_available']) : ''; ?>">
            </div>
        </div>
        
        <div class="form-group">
            <label for="description">Deskripsi Lengkap</label>
            <textarea id="description" name="description" class="form-control" placeholder="Masukkan spesifikasi produk, keunggulan, dan saran pengaplikasian..."><?php echo isset($_POST['description']) ? htmlspecialchars($_POST['description']) : ''; ?></textarea>
        </div>
        
        <div class="form-group">
            <label for="image">Gambar Produk</label>
            <input type="file" id="image" name="image" class="form-control" accept="image/*">
            <span style="font-size: 11px; color: var(--text-muted); margin-top: 5px; display: block;">Format file didukung: JPG, JPEG, PNG, WEBP. Maksimal ukuran 2MB.</span>
        </div>
        
        <div class="form-group" style="display: flex; align-items: center; gap: 10px;">
            <input type="checkbox" id="is_featured" name="is_featured" style="width: auto; margin-right: 5px;" <?php echo isset($_POST['is_featured']) ? 'checked' : ''; ?>>
            <label for="is_featured" style="display: inline; margin-bottom: 0; cursor: pointer;">Tampilkan sebagai Produk Unggulan di Beranda</label>
        </div>
        
        <div style="display: flex; gap: 15px; margin-top: 30px;">
            <button type="submit" name="add_product" class="btn-submit">Simpan Produk</button>
            <a href="products.php" class="btn-cancel">Batal</a>
        </div>
    </form>
</div>

<?php require_once 'includes/footer.php'; ?>
