<?php
/**
 * Complete Menu System Test
 * Tests: Filter creation → Item creation with image upload → Client retrieval
 */

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

// Test server location
$test_dir = __DIR__;
$upload_dir = $test_dir . '/../assets/uploads/menu/';

// Create upload directory if it doesn't exist
if (!is_dir($upload_dir)) {
    mkdir($upload_dir, 0755, true);
}

// Simulated response tracking
$results = [];

try {
    // 1. Create a test filter (Breakfast)
    $results['step1_create_filter'] = 'Testing filter creation...';
    
    // Direct database connection for testing
    require_once 'config.php';
    
    // Test 1: Insert filter
    $filter_name = 'Breakfast';
    $filter_desc = 'Morning delights and fresh starts';
    
    $query = "INSERT INTO menu_filters (filter_name, description, display_order, created_at, updated_at) 
              VALUES (?, ?, ?, NOW(), NOW())";
    $stmt = $conn->prepare($query);
    $order = 1;
    $stmt->bind_param('ssi', $filter_name, $filter_desc, $order);
    $stmt->execute();
    $filter_id = $conn->insert_id;
    
    $results['step1_create_filter'] = [
        'status' => 'success',
        'filter_id' => $filter_id,
        'filter_name' => $filter_name
    ];
    
    // Test 2: Create subcategories for this filter
    $results['step2_create_subcategories'] = 'Creating subcategories...';
    
    $subcategories = ['Vegetarian', 'Non-Vegetarian', 'Egg'];
    $sub_ids = [];
    
    foreach ($subcategories as $index => $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 = $index + 1;
        $stmt->bind_param('isi', $filter_id, $sub_name, $order);
        $stmt->execute();
        $sub_ids[$sub_name] = $conn->insert_id;
    }
    
    $results['step2_create_subcategories'] = [
        'status' => 'success',
        'subcategories' => $sub_ids
    ];
    
    // Test 3: Create a test menu item with image
    $results['step3_create_menu_item'] = 'Creating menu item with image...';
    
    // Create a simple test image (1x1 pixel PNG)
    $test_image_data = base64_decode(
        'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='
    );
    $temp_file = $upload_dir . 'test_upload_' . uniqid() . '.png';
    file_put_contents($temp_file, $test_image_data);
    
    $item_name = 'Pancakes with Syrup';
    $item_desc = 'Fluffy pancakes with maple syrup and butter';
    $item_price = 8.99;
    
    // Simulate file upload
    $filename = 'menu_' . time() . '_' . bin2hex(random_bytes(4)) . '.png';
    $filepath = $upload_dir . $filename;
    $web_path = 'assets/uploads/menu/' . $filename;
    
    copy($temp_file, $filepath);
    
    // Insert item into database
    $sub_id = $sub_ids['Vegetarian'];
    $query = "INSERT INTO menu_items (subcategory_id, item_name, description, price, image_path, created_at, updated_at) 
              VALUES (?, ?, ?, ?, ?, NOW(), NOW())";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('issds', $sub_id, $item_name, $item_desc, $item_price, $web_path);
    $stmt->execute();
    $item_id = $conn->insert_id;
    
    $results['step3_create_menu_item'] = [
        'status' => 'success',
        'item_id' => $item_id,
        'item_name' => $item_name,
        'image_path' => $web_path,
        'file_exists' => file_exists($filepath),
        'file_size' => filesize($filepath)
    ];
    
    // Test 4: Verify data retrieval via API
    $results['step4_verify_api'] = 'Verifying API retrieval...';
    
    // Get filters
    $query = "SELECT * FROM menu_filters WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('i', $filter_id);
    $stmt->execute();
    $filter_result = $stmt->get_result()->fetch_assoc();
    
    // Get menu hierarchy
    $query = "SELECT 
                f.id as filter_id, 
                f.filter_name,
                s.id as subcategory_id,
                s.subcategory_name,
                m.id as item_id,
                m.item_name,
                m.price,
                m.image_path
              FROM menu_filters f
              LEFT JOIN menu_subcategories s ON f.id = s.filter_id
              LEFT JOIN menu_items m ON s.id = m.subcategory_id
              WHERE f.id = ?
              ORDER BY f.display_order, s.display_order";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('i', $filter_id);
    $stmt->execute();
    $hierarchy = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    
    $results['step4_verify_api'] = [
        'status' => 'success',
        'filter_retrieved' => $filter_result !== null,
        'items_count' => count($hierarchy),
        'hierarchy_sample' => $hierarchy[0] ?? null
    ];
    
    // Test 5: Check image accessibility
    $results['step5_image_accessibility'] = 'Checking image paths...';
    
    $image_url = 'http://localhost/rest_table/' . $web_path;
    $results['step5_image_accessibility'] = [
        'status' => 'success',
        'physical_path' => $filepath,
        'web_path' => $web_path,
        'web_url' => $image_url,
        'file_exists_on_disk' => file_exists($filepath),
        'file_is_readable' => is_readable($filepath),
        'file_permissions' => substr(sprintf('%o', fileperms($filepath)), -4)
    ];
    
    // Test 6: Cleanup test image
    if (file_exists($temp_file)) {
        unlink($temp_file);
    }
    
    $results['summary'] = [
        'status' => 'success',
        'message' => 'All tests passed!',
        'filter_id' => $filter_id,
        'item_id' => $item_id,
        'next_step' => 'Visit menu.php and check if Breakfast filter appears with Pancakes item'
    ];
    
} catch (Exception $e) {
    $results['error'] = [
        'status' => 'error',
        'message' => $e->getMessage(),
        'trace' => $e->getTraceAsString()
    ];
}

echo json_encode($results, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
?>
