<?php
require_once __DIR__ . '/config.php';
requireAdmin();
$pdo = getDB();
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$product = null;
if ($id) {
    $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
    $stmt->execute([$id]);
    $product = $stmt->fetch(PDO::FETCH_ASSOC);
}
$categories = $pdo->query("SELECT id, name FROM product_categories ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);

$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $slug = trim($_POST['slug'] ?? '');
    $category_id = !empty($_POST['category_id']) ? (int)$_POST['category_id'] : null;
    $description = trim($_POST['description'] ?? '');
    $specifications = trim($_POST['specifications'] ?? '');
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    $sort_order = (int)($_POST['sort_order'] ?? 0);
    if (!$name) $errors[] = 'Name is required.';
    if (!$slug) $slug = preg_replace('/[^a-z0-9]+/', '-', strtolower($name));
    $imageName = $product['image'] ?? null;
    if (empty($errors)) {
        if ($id) {
            if (!empty($_FILES['image']['name'])) {
                $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
                if (in_array($ext, ['jpg','jpeg','png','gif','webp'])) {
                    $imageName = 'p' . $id . '_' . time() . '.' . $ext;
                    move_uploaded_file($_FILES['image']['tmp_name'], UPLOAD_PATH . 'products/' . $imageName);
                }
            }
            $stmt = $pdo->prepare("UPDATE products SET name=?, slug=?, category_id=?, description=?, specifications=?, image=?, is_active=?, sort_order=? WHERE id=?");
            $stmt->execute([$name, $slug, $category_id, $description, $specifications, $imageName, $is_active, $sort_order, $id]);
        } else {
            $stmt = $pdo->prepare("INSERT INTO products (name, slug, category_id, description, specifications, image, is_active, sort_order) VALUES (?,?,?,?,?,?,?,?)");
            $stmt->execute([$name, $slug, $category_id, $description, $specifications, null, $is_active, $sort_order]);
            $newId = $pdo->lastInsertId();
            if (!empty($_FILES['image']['name']) && $newId) {
                $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
                if (in_array($ext, ['jpg','jpeg','png','gif','webp'])) {
                    $imageName = 'p' . $newId . '_' . time() . '.' . $ext;
                    move_uploaded_file($_FILES['image']['tmp_name'], UPLOAD_PATH . 'products/' . $imageName);
                    $pdo->prepare("UPDATE products SET image = ? WHERE id = ?")->execute([$imageName, $newId]);
                }
            }
        }
        header('Location: products.php');
        exit;
    }
}
$pageTitle = $product ? 'Edit Product' : 'Add Product';
require_once __DIR__ . '/includes/header.php';
?>
<div class="admin-page">
    <h1><?php echo $product ? 'Edit Product' : 'Add Product'; ?></h1>
    <?php foreach ($errors as $e): ?>
    <p class="error"><?php echo htmlspecialchars($e); ?></p>
    <?php endforeach; ?>
    <form method="post" enctype="multipart/form-data" class="admin-form">
        <label>Name *</label>
        <input type="text" name="name" required value="<?php echo htmlspecialchars($product['name'] ?? $_POST['name'] ?? ''); ?>">
        <label>Slug</label>
        <input type="text" name="slug" value="<?php echo htmlspecialchars($product['slug'] ?? $_POST['slug'] ?? ''); ?>">
        <label>Category</label>
        <select name="category_id">
            <option value="">— Select —</option>
            <?php foreach ($categories as $c): ?>
            <option value="<?php echo (int)$c['id']; ?>" <?php echo (($product['category_id'] ?? '') == $c['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($c['name']); ?></option>
            <?php endforeach; ?>
        </select>
        <label>Description</label>
        <textarea name="description" rows="4"><?php echo htmlspecialchars($product['description'] ?? $_POST['description'] ?? ''); ?></textarea>
        <label>Specifications</label>
        <textarea name="specifications" rows="2"><?php echo htmlspecialchars($product['specifications'] ?? $_POST['specifications'] ?? ''); ?></textarea>
        <label>Image</label>
        <p class="muted" style="margin:0 0 8px; font-size:0.85rem;">Recommended product image size: <strong>1200×900</strong> (4:3) or <strong>1200×750</strong> (8:5). Use a clean background.</p>
        <?php if (!empty($product['image'])): ?>
        <p>Current: <img src="<?php echo ADMIN_SITE_ROOT . '/' . UPLOAD_URL . 'products/' . $product['image']; ?>" alt="" style="max-width:120px;"></p>
        <?php endif; ?>
        <input type="file" name="image" accept="image/*">
        <label>Sort order</label>
        <input type="number" name="sort_order" value="<?php echo (int)($product['sort_order'] ?? $_POST['sort_order'] ?? 0); ?>">
        <label><input type="checkbox" name="is_active" value="1" <?php echo ($product['is_active'] ?? 1) ? 'checked' : ''; ?>> Active</label>
        <button type="submit" class="btn">Save</button>
        <a href="products.php" class="btn btn-secondary">Cancel</a>
    </form>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
