<?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();
$categoryIds = array_map(fn($c) => (int) $c['id'], $categories);

$errors = [];
$editProduct = null;

if (isset($_GET['edit'])) {
    $editId = (int) $_GET['edit'];
    $stmt = $pdo->prepare('SELECT * FROM products WHERE id = ? LIMIT 1');
    $stmt->execute([$editId]);
    $editProduct = $stmt->fetch();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'toggle') {
        $id = (int) ($_POST['id'] ?? 0);
        $stmt = $pdo->prepare('UPDATE products SET is_active = IF(is_active = 1, 0, 1) WHERE id = ?');
        $stmt->execute([$id]);
        flash_message('success', 'Status produk diperbarui.');
        redirect(base_url('admin/products.php'));
    }

    if ($action === 'delete') {
        $id = (int) ($_POST['id'] ?? 0);
        $stmt = $pdo->prepare('DELETE FROM products WHERE id = ?');
        $stmt->execute([$id]);
        flash_message('success', 'Produk berhasil dihapus.');
        redirect(base_url('admin/products.php'));
    }

    if ($action === 'update') {
        $id = (int) ($_POST['id'] ?? 0);
        $categoryId = (int) ($_POST['category_id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $price = trim($_POST['price'] ?? '');
        $stock = trim($_POST['stock'] ?? '');
        $weight = trim($_POST['weight_gram'] ?? '');
        $isActive = isset($_POST['is_active']) ? 1 : 0;

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

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

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

        if (!in_array($categoryId, $categoryIds, true)) {
            $errors['category_id'] = 'Kategori wajib dipilih.';
        }

        $currentStmt = $pdo->prepare('SELECT photo FROM products WHERE id = ? LIMIT 1');
        $currentStmt->execute([$id]);
        $current = $currentStmt->fetch();
        $photo = $current['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-]+/', '-', $name), '-'));
            $stmt = $pdo->prepare('UPDATE products SET category_id = ?, name = ?, slug = ?, description = ?, price = ?, stock = ?, weight_gram = ?, photo = ?, is_active = ? WHERE id = ?');
            $stmt->execute([
                $categoryId,
                $name,
                $slug,
                $description,
                $price,
                $stock,
                $weight !== '' ? $weight : null,
                $photo,
                $isActive,
                $id,
            ]);
            flash_message('success', 'Produk berhasil diperbarui.');
            redirect(base_url('admin/products.php'));
        }
    }
}

$products = $pdo->query('SELECT p.*, c.name AS category_name FROM products p LEFT JOIN categories c ON c.id = p.category_id ORDER BY p.created_at DESC')->fetchAll();
?>

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

<?php if ($editProduct): ?>
    <div class="card shadow-sm mb-4">
        <div class="card-body">
            <h5 class="fw-bold">Edit Produk</h5>
            <form method="post" enctype="multipart/form-data">
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="id" value="<?= (int) $editProduct['id']; ?>">
                <div class="row g-3">
                    <div class="col-md-4">
                        <label>Kategori</label>
                        <select class="form-select" name="category_id" required>
                            <?php foreach ($categories as $category): ?>
                                <option value="<?= (int) $category['id']; ?>" <?= (int) $editProduct['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-4">
                        <label>Nama</label>
                        <input class="form-control" type="text" name="name" value="<?= sanitize($editProduct['name']); ?>" required>
                        <?php if (!empty($errors['name'])): ?><small class="error"><?= sanitize($errors['name']); ?></small><?php endif; ?>
                    </div>
                    <div class="col-md-4">
                        <label>Harga</label>
                        <input class="form-control" type="number" name="price" value="<?= sanitize($editProduct['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-12">
                        <label>Deskripsi</label>
                        <textarea class="form-control" name="description" rows="3"><?= sanitize($editProduct['description']); ?></textarea>
                    </div>
                    <div class="col-md-4">
                        <label>Stok</label>
                        <input class="form-control" type="number" name="stock" value="<?= sanitize($editProduct['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($editProduct['weight_gram']); ?>" min="0">
                    </div>
                    <div class="col-md-4">
                        <label>Ganti Foto</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-4">
                        <div class="form-check mt-4">
                            <input class="form-check-input" type="checkbox" name="is_active" id="edit_active" <?= (int) $editProduct['is_active'] === 1 ? 'checked' : ''; ?>>
                            <label class="form-check-label" for="edit_active">Aktif</label>
                        </div>
                    </div>
                </div>
                <button class="btn mt-3" type="submit">Update</button>
                <a class="btn btn-sm" href="<?= base_url('admin/products.php'); ?>">Batal</a>
            </form>
        </div>
    </div>
<?php endif; ?>

<div class="card shadow-sm">
    <div class="card-body table-responsive">
        <table class="table align-middle">
            <thead>
                <tr>
                    <th>Produk</th>
                    <th>Kategori</th>
                    <th>Harga</th>
                    <th>Stok</th>
                    <th>Status</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($products as $product): ?>
                    <tr>
                        <td><?= sanitize($product['name']); ?></td>
                        <td><?= sanitize($product['category_name'] ?? '-'); ?></td>
                        <td><?= format_currency($product['price']); ?></td>
                        <td><?= (int) $product['stock']; ?></td>
                        <td><?= (int) $product['is_active'] === 1 ? 'Aktif' : 'Nonaktif'; ?></td>
                        <td>
                            <a class="btn btn-sm" href="<?= base_url('admin/products.php?edit=' . (int) $product['id']); ?>">Edit</a>
                            <form method="post" class="d-inline">
                                <input type="hidden" name="action" value="toggle">
                                <input type="hidden" name="id" value="<?= (int) $product['id']; ?>">
                                <button class="btn btn-sm" type="submit">Toggle</button>
                            </form>
                            <button class="btn btn-sm" data-bs-toggle="modal" data-bs-target="#deleteProduct<?= (int) $product['id']; ?>">Hapus</button>
                        </td>
                    </tr>
                    <div class="modal fade" id="deleteProduct<?= (int) $product['id']; ?>" tabindex="-1" aria-hidden="true">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title">Hapus Produk</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                </div>
                                <div class="modal-body">Yakin hapus produk <?= sanitize($product['name']); ?>?</div>
                                <div class="modal-footer">
                                    <form method="post">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= (int) $product['id']; ?>">
                                        <button class="btn" type="submit">Ya, Hapus</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

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