<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';

$auth = new Auth();
$auth->requireRole(['restaurant_admin', 'restaurant_manager', 'cashier', 'kitchen_staff', 'waiter']);

$csrf = new CSRF();
$restaurantId = $auth->restaurantId();
$userId = $auth->userId();
$db = Database::getInstance();

$action = $_GET['action'] ?? $_POST['action'] ?? '';
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET' && $action === 'get') {
    $id = (int)($_GET['id'] ?? 0);
    $cat = $db->query("SELECT * FROM categories WHERE id = ? AND restaurant_id = ?", [$id, $restaurantId])->fetch();
    if ($cat) {
        jsonResponse(true, 'ok', ['category' => $cat]);
    }
    jsonResponse(false, 'Category not found');
}

if ($method === 'POST') {
    if (empty($_POST['csrf_token']) || !$csrf->verify($_POST['csrf_token'])) {
        jsonResponse(false, 'Invalid CSRF token');
    }

    if ($action === 'add' || $action === 'edit') {
        $id = (int)($_POST['category_id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $sortOrder = (int)($_POST['sort_order'] ?? 0);
        $status = (int)($_POST['status'] ?? 1);
        $isFeatured = isset($_POST['is_featured']) ? 1 : 0;
        $availableDays = !empty($_POST['available_days']) ? implode(',', array_map('trim', $_POST['available_days'])) : null;
        $startTime = $_POST['start_time'] ?? null;
        $endTime = $_POST['end_time'] ?? null;

        if (empty($name)) {
            jsonResponse(false, 'Category name is required');
        }

        $slug = slugify($name);
        $upload = new Upload();
        $imagePath = null;

        if (!empty($_FILES['image']['name'])) {
            $result = $upload->uploadFile($_FILES['image'], 'categories/' . $restaurantId);
            if ($result['success']) {
                $imagePath = $result['path'];
            } else {
                jsonResponse(false, 'Image upload failed: ' . implode(', ', $result['errors']));
            }
        }

        if ($action === 'add') {
            $newId = $db->insert('categories', [
                'restaurant_id' => $restaurantId,
                'name' => $name,
                'slug' => $slug,
                'description' => $description,
                'image' => $imagePath,
                'status' => $status,
                'sort_order' => $sortOrder,
                'is_featured' => $isFeatured,
                'available_days' => $availableDays,
                'start_time' => $startTime ?: null,
                'end_time' => $endTime ?: null,
            ]);

            $activityLog = new ActivityLog();
            $activityLog->log($userId, $restaurantId, 'menu', 'category_create', 'Category "' . $name . '" created');

            jsonResponse(true, 'Category created successfully');
        }

        if ($action === 'edit') {
            $existing = $db->query("SELECT id, image FROM categories WHERE id = ? AND restaurant_id = ?", [$id, $restaurantId])->fetch();
            if (!$existing) {
                jsonResponse(false, 'Category not found');
            }

            $updateData = [
                'name' => $name,
                'slug' => $slug,
                'description' => $description,
                'status' => $status,
                'sort_order' => $sortOrder,
                'is_featured' => $isFeatured,
                'available_days' => $availableDays,
                'start_time' => $startTime ?: null,
                'end_time' => $endTime ?: null,
            ];

            if ($imagePath) {
                $updateData['image'] = $imagePath;
            }

            $db->update('categories', $updateData, 'id = ? AND restaurant_id = ?', [$id, $restaurantId]);

            $activityLog = new ActivityLog();
            $activityLog->log($userId, $restaurantId, 'menu', 'category_update', 'Category "' . $name . '" updated');

            jsonResponse(true, 'Category updated successfully');
        }
    }

    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        $cat = $db->query("SELECT id, name FROM categories WHERE id = ? AND restaurant_id = ?", [$id, $restaurantId])->fetch();
        if (!$cat) {
            jsonResponse(false, 'Category not found');
        }

        $itemCount = $db->count('menu_items', 'category_id = ? AND restaurant_id = ?', [$id, $restaurantId]);
        if ($itemCount > 0) {
            jsonResponse(false, 'Cannot delete category with ' . $itemCount . ' menu items. Move or delete items first.');
        }

        $db->delete('categories', 'id = ? AND restaurant_id = ?', [$id, $restaurantId]);

        $activityLog = new ActivityLog();
        $activityLog->log($userId, $restaurantId, 'menu', 'category_delete', 'Category "' . $cat['name'] . '" deleted');

        jsonResponse(true, 'Category deleted successfully');
    }

    if ($action === 'toggle_status') {
        $id = (int)($_POST['id'] ?? 0);
        $cat = $db->query("SELECT id, name, status FROM categories WHERE id = ? AND restaurant_id = ?", [$id, $restaurantId])->fetch();
        if (!$cat) {
            jsonResponse(false, 'Category not found');
        }

        $newStatus = $cat['status'] ? 0 : 1;
        $db->update('categories', ['status' => $newStatus], 'id = ?', [$id]);

        jsonResponse(true, 'Category ' . ($newStatus ? 'activated' : 'deactivated') . ' successfully');
    }
}

jsonResponse(false, 'Invalid request');
