<?php
header('Content-Type: application/json');

require_once 'config.php';

try {
    // Create a test filter
    $filter_name = 'Lunch' . time();
    $query = "INSERT INTO menu_filters (filter_name, description, display_order, created_at, updated_at) 
              VALUES (?, ?, ?, NOW(), NOW())";
    $stmt = $conn->prepare($query);
    $order = 1;
    $desc = "Lunch items";
    $stmt->bind_param("ssi", $filter_name, $desc, $order);
    $stmt->execute();
    $filter_id = $conn->insert_id;
    
    if (!$filter_id) {
        throw new Exception("Failed to create filter");
    }

    // Create subcategories
    $subs = ['Vegetarian', 'Non-Vegetarian', 'Egg'];
    $sub_ids = [];
    foreach ($subs as $idx => $sub_name) {
        $query = "INSERT INTO menu_subcategories (filter_id, subcategory_name, display_order, created_at, updated_at) 
                  VALUES (?, ?, ?, NOW(), NOW())";
        $stmt = $conn->prepare($query);
        $order = $idx + 1;
        $stmt->bind_param("isi", $filter_id, $sub_name, $order);
        $stmt->execute();
        $sub_ids[] = $conn->insert_id;
    }

    // Create test menu item with image
    $test_image_data = base64_decode(
        'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='
    );
    $upload_dir = __DIR__ . '/../assets/uploads/menu/';
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }

    $filename = 'menu_' . time() . '_' . bin2hex(random_bytes(4)) . '.png';
    $filepath = $upload_dir . $filename;
    $web_path = 'assets/uploads/menu/' . $filename;
    file_put_contents($filepath, $test_image_data);

    // Insert item
    $item_name = 'Chicken Biryani';
    $description = 'Fragrant rice with spiced chicken';
    $price = 120.00;
    $sub_id = $sub_ids[1];
    $display_order = 1;
    $is_available = 1;
    
    $query = "INSERT INTO menu_items (subcategory_id, item_name, description, price, image_path, display_order, is_available, created_at, updated_at) 
              VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("issdsii", $sub_id, $item_name, $description, $price, $web_path, $display_order, $is_available);
    $stmt->execute();
    $item_id = $conn->insert_id;

    echo json_encode([
        'success' => true,
        'filter_id' => $filter_id,
        'filter_name' => $filter_name,
        'sub_ids' => $sub_ids,
        'item_id' => $item_id,
        'item_image' => $web_path
    ], JSON_PRETTY_PRINT);
} catch (Exception $e) {
    echo json_encode([
        'error' => $e->getMessage()
    ], JSON_PRETTY_PRINT);
}
?>

