<?php
class MenuCategory {
    private $pdo;
    
    public function __construct() { 
        $this->pdo = $GLOBALS['pdo']; 
    }
    
    public function all() { 
        return $this->pdo->query("SELECT * FROM menu_categories ORDER BY sort_order ASC, name ASC")->fetchAll(); 
    }
    
    public function find($id) { 
        $st = $this->pdo->prepare("SELECT * FROM menu_categories WHERE id=?"); 
        $st->execute([$id]); 
        return $st->fetch(); 
    }
    
    public function create($data) { 
        $st = $this->pdo->prepare("INSERT INTO menu_categories (name, name_en, description, description_en, sort_order) VALUES (?,?,?,?,?)"); 
        return $st->execute([
            $data['name']??'', 
            $data['name_en']??'', 
            $data['description']??'', 
            $data['description_en']??'', 
            (int)($data['sort_order']??0)
        ]); 
    }
    
    public function update($id, $data) { 
        // If only sort_order is provided, update only that field
        if (isset($data['sort_order']) && !isset($data['name'])) {
            $st = $this->pdo->prepare("UPDATE menu_categories SET sort_order=? WHERE id=?"); 
            return $st->execute([(int)$data['sort_order'], $id]);
        }
        // Otherwise update all fields
        $st = $this->pdo->prepare("UPDATE menu_categories SET name=?, name_en=?, description=?, description_en=?, sort_order=? WHERE id=?"); 
        return $st->execute([
            $data['name']??'', 
            $data['name_en']??'', 
            $data['description']??'', 
            $data['description_en']??'', 
            (int)($data['sort_order']??0), 
            $id
        ]); 
    }
    
    public function delete($id) { 
        $st = $this->pdo->prepare("DELETE FROM menu_categories WHERE id=?"); 
        return $st->execute([$id]); 
    }
}
