<?php
// Set headers for JSON response and CORS
header('Content-Type: application/json');
require_once '../config/cors.php';

// Include necessary files
require_once '../config/database.php';
require_once '../models/Category.php';
require_once '../models/Product.php';
require_once '../middleware/auth.php';

// Initialize database and objects
$database = new Database();
$db = $database->getConnection();
$category = new Category($db);
$product = new Product($db);

// Get the request method
$method = $_SERVER['REQUEST_METHOD'];

// Handle the request based on the method
switch($method) {
    case 'GET':
        // Logic for single category remains the same
        if (isset($_GET['id'])) {
            $category->id = $_GET['id'];
            
            if ($category->getSingleCategory()) {
                // For a single category, we can still use slug to be consistent
                $productsResult = $product->getProducts(1, 100, $category->slug, null, null, null, null, 'created_at', 'DESC');
                
                $category_details = [
                    'id' => $category->id,
                    'name' => $category->name,
                    'slug' => $category->slug,
                    'description' => $category->description,
                    'image_url' => $category->image_url,
                    'products' => $productsResult['products']
                ];
                
                http_response_code(200);
                echo json_encode(['success' => true, 'category' => $category_details]);

            } else {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Category not found']);
            }
        } else {
            // Logic for all categories
            try {
                $categories = $category->getCategories();
                
                // Loop through each category to fetch its products
                foreach ($categories as &$cat) {
                    
                    // --- YEH LINE FIX KI GAYI HAI ---
                    // Hum ab ID ki jagah SLUG bhej rahe hain
                    $productsResult = $product->getProducts(1, 100, $cat['slug'], null, null, null, null, 'created_at', 'DESC');
                    
                    // Add the fetched products into the category's data
                    $cat['products'] = $productsResult['products'];
                }
                unset($cat); // Unset the reference
                
                http_response_code(200);
                echo json_encode([
                    'success' => true,
                    'categories' => $categories
                ]);
            } catch (Exception $e) {
                http_response_code(500);
                echo json_encode([
                    'success' => false,
                    'message' => 'Internal server error: ' . $e->getMessage()
                ]);
            }
        }
        break;

    // POST and default cases remain unchanged
    case 'POST':
        $user = requireAdmin();
        $data = json_decode(file_get_contents("php://input"));

        if (!$data || !isset($data->name) || !isset($data->slug)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Name and slug are required']);
            break;
        }

        $category->name = $data->name;
        $category->slug = $data->slug;
        $category->description = $data->description ?? '';
        $category->image_url = $data->image_url ?? '';

        try {
            if ($category->create()) {
                http_response_code(201);
                echo json_encode(['success' => true, 'message' => 'Category created successfully']);
            } else {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Failed to create category.']);
            }
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Internal server error: ' . $e->getMessage()]);
        }
        break;

    default:
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Method not allowed']);
        break;
}