<?php

namespace App\Models;

use App\Core\Model;
use PDOException;

class Product extends Model
{
    public function getAll()
    {
        try {
            return $this->fetchAll("SELECT p.*, c.name as category_name FROM products p JOIN categories c ON p.category_id = c.id WHERE p.is_active = 1 ORDER BY c.sort_order, p.name");
        } catch (PDOException $e) {
            return $this->getDummyData();
        }
    }

    public function getBySlug($slug)
    {
        try {
            $product = $this->fetchOne("SELECT * FROM products WHERE slug = ?", [$slug]);
            if ($product) {
                $product['options'] = $this->fetchAll("SELECT * FROM product_options WHERE product_id = ?", [$product['id']]);
                $product['ingredients'] = $this->fetchAll("SELECT i.name FROM product_ingredients pi JOIN ingredients i ON pi.ingredient_id = i.id WHERE pi.product_id = ?", [$product['id']]);
            }
            return $product;
        } catch (PDOException $e) {
            // Dummy fallback
            $all = $this->getDummyData();
            foreach ($all as $p) {
                if ($p['slug'] === $slug) return $p;
            }
            return null;
        }
    }

    private function getDummyData()
    {
        return [
            [
                'id' => 1, 'category_name' => 'Hambúrgueres de Siri', 'name' => 'Hambúrguer de Siri Clássico', 
                'slug' => 'hamburguer-siri-classico', 'base_price' => 25.00, 'description' => 'A receita secreta original!',
                'image_url' => 'assets/img/burger.png', 'options' => [], 'ingredients' => [['name' => 'Carne de Siri'], ['name' => 'Alface'], ['name' => 'Tomate']]
            ],
            [
                'id' => 2, 'category_name' => 'Hambúrgueres de Siri', 'name' => 'Siri Duplo', 
                'slug' => 'siri-duplo', 'base_price' => 35.00, 'description' => 'Duas carnes suculentas.',
                'image_url' => 'assets/img/burger_double.png', 'options' => [], 'ingredients' => []
            ],
            [
                'id' => 3, 'category_name' => 'Bebidas', 'name' => 'Refrigerante Kelp', 
                'slug' => 'kelp-shake', 'base_price' => 12.00, 'description' => 'Refrescante!',
                'image_url' => 'assets/img/drink.png', 'options' => [], 'ingredients' => []
            ]
        ];
    }
}
