<?php
require_once 'admin/core/Database.php';

class Category {
    private $db;

    public function __construct() {
        $this->db = new Database();
    }

    private function generateSlug($title) {
        $slug = strtolower(trim($title));
        $slug = preg_replace('/[^a-z0-9-]+/', '-', $slug);
        $slug = preg_replace('/-+/', '-', $slug);
        return trim($slug, '-');
    }

    public function add($data) {
        $slug = $this->generateSlug($data['cat_title']);

        $stmt = $this->db->conn->prepare("
            INSERT INTO category 
            (parent_id, cat_title, cat_slug,  cat_image, status)
            VALUES (:parent_id, :cat_title, :cat_slug, :cat_image, :status)
        ");

        $stmt->execute([
            ':parent_id' => $data['parent_id'],
            ':cat_title' => $data['cat_title'],
            ':cat_slug' => $slug,
            // ':cat_description' => $data['cat_description'],
            ':cat_image' => $data['cat_image'],
            ':status' => $data['status']
        ]);
    }

    public function getAll() {
        $stmt = $this->db->conn->query("SELECT * FROM category ORDER BY id DESC");
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function get($id) {
        $stmt = $this->db->conn->prepare("SELECT * FROM category WHERE id = :id");
        $stmt->execute([':id' => $id]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    public function update($id, $data) {
        $slug = $this->generateSlug($data['cat_title']);

        $stmt = $this->db->conn->prepare("
            UPDATE category SET 
            parent_id = :parent_id,
            cat_title = :cat_title,
            cat_slug = :cat_slug,
            cat_image = :cat_image,
            status = :status
            WHERE id = :id
        ");

        $stmt->execute([
            ':parent_id' => $data['parent_id'],
            ':cat_title' => $data['cat_title'],
            ':cat_slug' => $slug,
            // ':cat_description' => $data['cat_description'],
            ':cat_image' => $data['cat_image'],
            ':status' => $data['status'],
            ':id' => $id
        ]);
    }

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