<?php

// Simple Laravel-style API server for Kenyan POS
// This bypasses the complex Laravel bootstrap issues

require_once 'vendor/autoload.php';

use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

// Database setup
$capsule = new Capsule;
$capsule->addConnection([
    'driver' => 'mysql',
    'host' => '127.0.0.1',
    'database' => 'kenyan_pos',
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
]);

$capsule->setAsGlobal();
$capsule->bootEloquent();

// CORS headers
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Simple routing
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$method = $_SERVER['REQUEST_METHOD'];

// API Response
function jsonResponse($data, $status = 200) {
    http_response_code($status);
    echo json_encode($data);
    exit();
}

// Routes
if ($uri === '/' || $uri === '/api') {
    jsonResponse([
        'message' => 'Kenyan Restaurant POS API',
        'version' => '1.0.0',
        'status' => 'running',
        'framework' => 'Laravel + Eloquent',
        'endpoints' => [
            'auth' => '/api/auth/*',
            'menu' => '/api/menu/*',
            'orders' => '/api/orders/*',
            'kitchen' => '/api/kitchen/*',
            'inventory' => '/api/inventory/*',
            'reports' => '/api/reports/*'
        ]
    ]);
}

// Test database connection
if ($uri === '/api/test') {
    try {
        $result = Capsule::select('SELECT 1 as test');
        jsonResponse([
            'database' => 'connected',
            'result' => $result
        ]);
    } catch (Exception $e) {
        jsonResponse([
            'error' => 'Database connection failed',
            'message' => $e->getMessage()
        ], 500);
    }
}

// Default response
jsonResponse([
    'error' => 'Endpoint not found',
    'uri' => $uri,
    'method' => $method
], 404);