<?php
require_once '../app/Models/MenuCategory.php';

class MenuCategoryController {
    private $model;
    
    public function __construct() { 
        $this->auth(); 
        $this->model = new MenuCategory(); 
    }
    
    private function auth() { 
        if (!isset($_SESSION['user_id'])) { 
            redirect('login'); 
            exit; 
        } 
    }
    
    public function index() { 
        $this->view('menu/categories', ['categories' => $this->model->all()]); 
    }
    
    public function create() { 
        $this->view('menu/categories_create'); 
    }
    
    public function store() { 
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { 
            redirect('menu/categories'); 
            exit; 
        } 
        
        $name = trim($_POST['name'] ?? ''); 
        if ($name === '') { 
            $_SESSION['error'] = 'Nazwa jest wymagana'; 
            redirect('menu/categories/create'); 
            exit; 
        } 
        
        $this->model->create([
            'name' => $name,
            'name_en' => $_POST['name_en'] ?? '',
            'description' => $_POST['description'] ?? '',
            'description_en' => $_POST['description_en'] ?? '',
            'sort_order' => $_POST['sort_order'] ?? 0
        ]); 
        
        $_SESSION['success'] = 'Kategoria została utworzona'; 
        redirect('menu/categories'); 
    }
    
    public function edit($id) { 
        $c = $this->model->find($id); 
        if (!$c) { 
            $_SESSION['error'] = 'Nie znaleziono'; 
            redirect('menu/categories'); 
            exit; 
        } 
        $this->view('menu/categories_edit', ['category' => $c]); 
    }
    
    public function update($id) { 
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { 
            redirect('menu/categories'); 
            exit; 
        } 
        
        $name = trim($_POST['name'] ?? ''); 
        if ($name === '') { 
            $_SESSION['error'] = 'Nazwa jest wymagana'; 
            redirect('menu/categories/' . $id . '/edit'); 
            exit; 
        } 
        
        $this->model->update($id, [
            'name' => $name,
            'name_en' => $_POST['name_en'] ?? '',
            'description' => $_POST['description'] ?? '',
            'description_en' => $_POST['description_en'] ?? '',
            'sort_order' => $_POST['sort_order'] ?? 0
        ]); 
        
        $_SESSION['success'] = 'Zaktualizowano'; 
        redirect('menu/categories'); 
    }
    
    public function delete($id) { 
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { 
            redirect('menu/categories'); 
            exit; 
        } 
        
        $this->model->delete($id); 
        $_SESSION['success'] = 'Usunięto'; 
        redirect('menu/categories'); 
    }
    
    public function reorder() {
        header('Content-Type: application/json');
        
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            echo json_encode(['success' => false, 'error' => 'Invalid method']);
            exit;
        }
        
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            echo json_encode(['success' => false, 'error' => 'Invalid JSON: ' . json_last_error_msg()]);
            exit;
        }
        
        $order = $input['order'] ?? [];
        
        if (empty($order)) {
            echo json_encode(['success' => false, 'error' => 'No order provided']);
            exit;
        }
        
        try {
            foreach ($order as $index => $id) {
                $result = $this->model->update($id, ['sort_order' => $index]);
                if (!$result) {
                    throw new Exception("Failed to update category ID: $id");
                }
            }
            echo json_encode(['success' => true]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
        exit;
    }
    
    private function view($v, $d = []) { 
        extract($d); 
        require_once "../app/Views/$v.php"; 
    }
}
