<?php
require_once __DIR__ . '/../includes/auth.php';
require_owner_or_admin();
require_once __DIR__ . '/../includes/header_admin.php';
require_once __DIR__ . '/../includes/upload.php';
$pdo = require __DIR__ . '/../config/pdo.php';

$categories = $pdo->query('SELECT id, name FROM categories WHERE is_active = 1 ORDER BY name')->fetchAll();

$errors = [];
$values = [
    'category_id' => '',
    'name' => '',
    'description' => '',
    'price' => '',
    'stock' => '',
    'weight_gram' => '',
    'is_active' => 1,
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $values['category_id'] = (int) ($_POST['category_id'] ?? 0);
    $values['name'] = trim($_POST['name'] ?? '');
    $values['description'] = trim($_POST['description'] ?? '');
    $values['price'] = trim($_POST['price'] ?? '');
    $values['stock'] = trim($_POST['stock'] ?? '');
    $values['weight_gram'] = trim($_POST['weight_gram'] ?? '');
    $values['is_active'] = isset($_POST['is_active']) ? 1 : 0;

    if ($values['name'] === '') {
        $errors['name'] = 'Nama produk wajib diisi.';
    }

    if ($values['price'] === '' || !is_numeric($values['price'])) {
        $errors['price'] = 'Harga tidak valid.';
    }

    if ($values['stock'] === '' || !is_numeric($values['stock'])) {
        $errors['stock'] = 'Stok tidak valid.';
    }

    $categoryIds = array_map(fn($c) => (int) $c['id'], $categories);
    if (!in_array($values['category_id'], $categoryIds, true)) {
        $errors['category_id'] = 'Kategori wajib dipilih.';
    }

    $photo = null;
    if (!$errors && isset($_FILES['photo']) && $_FILES['photo']['error'] !== UPLOAD_ERR_NO_FILE) {
        $upload = handle_upload($_FILES['photo'], ['image/jpeg', 'image/png', 'image/webp'], 2 * 1024 * 1024, __DIR__ . '/../uploads');
        if (!$upload['ok']) {
            $errors['photo'] = $upload['error'];
        } else {
            $photo = $upload['filename'];
        }
    }

    if (!$errors) {
        $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $values['name']), '-'));
        $stmt = $pdo->prepare('INSERT INTO products (category_id, name, slug, description, price, stock, weight_gram, photo, is_active) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
        $stmt->execute([
            $values['category_id'],
            $values['name'],
            $slug,
            $values['description'],
            $values['price'],
            $values['stock'],
            $values['weight_gram'] !== '' ? $values['weight_gram'] : null,
            $photo,
            $values['is_active'],
        ]);
        flash_message('success', 'Produk berhasil ditambahkan.');
        redirect(base_url('admin/products.php'));
    }
}
?>

<h2 class="fw-bold mb-4">Tambah Produk</h2>

<div class="card shadow-sm">
    <div class="card-body">
        <form method="post" enctype="multipart/form-data">
            <div class="row g-3">
                <div class="col-md-6">
                    <label>Kategori</label>
                    <select class="form-select" name="category_id" required>
                        <option value="">Pilih kategori</option>
                        <?php foreach ($categories as $category): ?>
                            <option value="<?= (int) $category['id']; ?>" <?= (int) $values['category_id'] === (int) $category['id'] ? 'selected' : ''; ?>>
                                <?= sanitize($category['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <?php if (!empty($errors['category_id'])): ?><small class="error"><?= sanitize($errors['category_id']); ?></small><?php endif; ?>
                </div>
                <div class="col-md-6">
                    <label>Nama Produk</label>
                    <input class="form-control" type="text" name="name" value="<?= sanitize($values['name']); ?>" required>
                    <?php if (!empty($errors['name'])): ?><small class="error"><?= sanitize($errors['name']); ?></small><?php endif; ?>
                </div>
                <div class="col-md-12">
                    <label>Deskripsi</label>
                    <textarea class="form-control" name="description" rows="3"><?= sanitize($values['description']); ?></textarea>
                </div>
                <div class="col-md-4">
                    <label>Harga</label>
                    <input class="form-control" type="number" name="price" value="<?= sanitize($values['price']); ?>" min="0" step="1000" required>
                    <?php if (!empty($errors['price'])): ?><small class="error"><?= sanitize($errors['price']); ?></small><?php endif; ?>
                </div>
                <div class="col-md-4">
                    <label>Stok</label>
                    <input class="form-control" type="number" name="stock" value="<?= sanitize($values['stock']); ?>" min="0" required>
                    <?php if (!empty($errors['stock'])): ?><small class="error"><?= sanitize($errors['stock']); ?></small><?php endif; ?>
                </div>
                <div class="col-md-4">
                    <label>Berat (gram)</label>
                    <input class="form-control" type="number" name="weight_gram" value="<?= sanitize($values['weight_gram']); ?>" min="0">
                </div>
                <div class="col-md-6">
                    <label>Foto Produk</label>
                    <input class="form-control" type="file" name="photo" accept="image/*">
                    <?php if (!empty($errors['photo'])): ?><small class="error"><?= sanitize($errors['photo']); ?></small><?php endif; ?>
                </div>
                <div class="col-md-6 d-flex align-items-center">
                    <div class="form-check mt-4">
                        <input class="form-check-input" type="checkbox" name="is_active" id="is_active" <?= (int) $values['is_active'] === 1 ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="is_active">Aktif</label>
                    </div>
                </div>
            </div>
            <button class="btn mt-3" type="submit">Simpan Produk</button>
        </form>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/footer_admin.php'; ?>
