<?php

namespace App\Models;

use App\Core\Model;
use PDO;

class Category extends Model {
    public function search($params = []) {
        $sql = "SELECT * FROM categories WHERE 1=1";
        $binds = [];

        if (!empty($params['search'])) {
            $sql .= " AND name LIKE :search";
            $binds['search'] = '%' . $params['search'] . '%';
        }

        if (isset($params['filter_status']) && $params['filter_status'] !== '') {
            $sql .= " AND is_active = :status";
            $binds['status'] = $params['filter_status'];
        }

        $sql .= " ORDER BY id DESC";
        $stmt = $this->db->prepare($sql);
        if (!empty($binds)) {
            $stmt->execute($binds);
        } else {
            $stmt->execute();
        }
        return $stmt->fetchAll();
    }

    public function find($id) {
        $stmt = $this->db->prepare("SELECT * FROM categories WHERE id = :id LIMIT 1");
        $stmt->execute(['id' => $id]);
        return $stmt->fetch();
    }

    public function save($data) {
        if (!empty($data['id'])) {
            $sql = "UPDATE categories SET 
                    name = :name, 
                    description = :description, 
                    is_active = :is_active 
                    WHERE id = :id";
            $stmt = $this->db->prepare($sql);
            return $stmt->execute([
                'name' => $data['name'],
                'description' => $data['description'] ?? null,
                'is_active' => $data['is_active'] ?? 1,
                'id' => $data['id']
            ]);
        } else {
            $sql = "INSERT INTO categories (name, description, is_active) 
                    VALUES (:name, :description, :is_active)";
            $stmt = $this->db->prepare($sql);
            return $stmt->execute([
                'name' => $data['name'],
                'description' => $data['description'] ?? null,
                'is_active' => $data['is_active'] ?? 1
            ]);
        }
    }

    public function delete($id) {
        $stmt = $this->db->prepare("DELETE FROM categories WHERE id = :id");
        return $stmt->execute(['id' => $id]);
    }

    public function toggleStatus($id) {
        $stmt = $this->db->prepare("UPDATE categories SET is_active = NOT is_active WHERE id = :id");
        return $stmt->execute(['id' => $id]);
    }
}
