<?php

namespace App\Models;

use App\Core\Model;
use PDO;

class ExpenseCategory extends Model {
    public function all() {
        $stmt = $this->db->query("SELECT * FROM expense_categories ORDER BY name ASC");
        return $stmt->fetchAll();
    }

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

    public function save($data) {
        $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $data['name'])));
        
        if (!empty($data['id'])) {
            $stmt = $this->db->prepare("UPDATE expense_categories SET name = :name, slug = :slug WHERE id = :id");
            return $stmt->execute([
                'name' => $data['name'],
                'slug' => $slug,
                'id' => $data['id']
            ]);
        } else {
            $stmt = $this->db->prepare("INSERT INTO expense_categories (name, slug) VALUES (:name, :slug)");
            $stmt->execute([
                'name' => $data['name'],
                'slug' => $slug
            ]);
            return $this->db->lastInsertId();
        }
    }

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