<?php

class CakeFlavor {
    private $pdo;

    public function __construct() {
        global $pdo;
        $this->pdo = $pdo;
    }

    public function all($activeOnly = true) {
        $sql = "SELECT * FROM cake_flavors";
        if ($activeOnly) {
            $sql .= " WHERE active = 1";
        }
        $sql .= " ORDER BY sort_order, name";
        $stmt = $this->pdo->query($sql);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function find($id) {
        $stmt = $this->pdo->prepare("SELECT * FROM cake_flavors WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    public function create($data) {
        $stmt = $this->pdo->prepare("INSERT INTO cake_flavors (name, name_en, image_url, sort_order, active) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([
            $data['name'],
            $data['name_en'] ?? null,
            $data['image_url'] ?? null,
            $data['sort_order'] ?? 0,
            $data['active'] ?? 1
        ]);
        return $this->pdo->lastInsertId();
    }

    public function update($id, $data) {
        $stmt = $this->pdo->prepare("UPDATE cake_flavors SET name = ?, name_en = ?, image_url = ?, sort_order = ?, active = ? WHERE id = ?");
        return $stmt->execute([
            $data['name'],
            $data['name_en'] ?? null,
            $data['image_url'] ?? null,
            $data['sort_order'] ?? 0,
            $data['active'] ?? 1,
            $id
        ]);
    }

    public function delete($id) {
        $stmt = $this->pdo->prepare("DELETE FROM cake_flavors WHERE id = ?");
        return $stmt->execute([$id]);
    }
}
