<?php

class CakeType {
    private $pdo;

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

    public function all($activeOnly = true) {
        $sql = "SELECT * FROM cake_types";
        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_types WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

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

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

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