<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Models\Category;
use App\Models\Setting;

class CategoryController {
    public function index() {
        if (!Auth::hasPermission('categories')) {
            redirect('/login');
            exit;
        }

        $categoryModel = new Category();
        
        $params = [
            'search' => $_GET['search'] ?? '',
            'filter_status' => $_GET['filter_status'] ?? '',
        ];

        $categories = $categoryModel->search($params);
        
        $settingModel = new Setting();
        $siteSettings = $settingModel->getAll();
        
        $title = 'Categories Master';
        
        $editingCategory = null;
        if (isset($_GET['edit_id'])) {
            $editingCategory = $categoryModel->find($_GET['edit_id']);
        }

        require_once __DIR__ . '/../../views/admin/categories.php';
    }

    public function save() {
        if (!Auth::hasPermission('categories')) {
            redirect('/login');
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $categoryModel = new Category();
            
            $data = [
                'id' => $_POST['id'] ?? null,
                'name' => $_POST['name'],
                'description' => $_POST['description'] ?: null,
                'is_active' => isset($_POST['is_active']) ? 1 : 0,
            ];

            try {
                $categoryModel->save($data);
                $_SESSION['toast'] = ['message' => $data['id'] ? 'Category updated!' : 'Category created!', 'type' => 'success'];
            } catch (\Exception $e) {
                $_SESSION['toast'] = ['message' => 'Error: ' . $e->getMessage(), 'type' => 'error'];
            }
        }
        redirect('/admin/categories');
        exit;
    }

    public function toggleStatus() {
        if (!Auth::hasPermission('categories')) {
            redirect('/login');
            exit;
        }

        if (isset($_GET['id'])) {
            $categoryModel = new Category();
            $categoryModel->toggleStatus($_GET['id']);
            $_SESSION['toast'] = ['message' => 'Status updated!', 'type' => 'info'];
        }
        redirect('/admin/categories');
        exit;
    }

    public function delete() {
        if (!Auth::hasPermission('categories')) {
            redirect('/login');
            exit;
        }

        if (isset($_GET['id'])) {
            $categoryModel = new Category();
            $categoryModel->delete($_GET['id']);
            $_SESSION['toast'] = ['message' => 'Category deleted!', 'type' => 'error'];
        }
        redirect('/admin/categories');
        exit;
    }
}
