<?php
/**
 * Main API Router
 * This file handles routing for clean URLs
 * 
 * URLs:
 * /api/admin/login     -> auth.php?action=login
 * /api/admin/stats     -> stats.php?type=admin
 * /api/blog            -> blogs.php
 * /api/blog/{id}       -> blogs.php?id={id}
 * /api/products        -> products.php
 * /api/products/{id}   -> products.php?id={id}
 * etc.
 */

require_once 'config.php';

// Get the request path
$requestUri = $_SERVER['REQUEST_URI'];
$path = parse_url($requestUri, PHP_URL_PATH);

// Remove /api prefix if present
$path = preg_replace('/^\/api/', '', $path);
$path = preg_replace('/^\/rhelektronik\.com\/api/', '', $path);

// Parse path segments
$segments = array_values(array_filter(explode('/', $path)));

// Route mapping
$route = $segments[0] ?? '';
$id = $segments[1] ?? null;

// Set ID in GET if present
if ($id) {
    $_GET['id'] = $id;
}

switch ($route) {
    case 'admin':
        $action = $segments[1] ?? '';
        if ($action === 'login') {
            $_GET['action'] = 'login';
            require 'auth.php';
        } elseif ($action === 'stats') {
            $_GET['type'] = 'admin';
            require 'stats.php';
        } elseif ($action === 'create-first-admin') {
            $_GET['action'] = 'create-first-admin';
            require 'auth.php';
        } else {
            errorResponse('Route not found', 404);
        }
        break;
        
    case 'blog':
        require 'blogs.php';
        break;
        
    case 'products':
        require 'products.php';
        break;
        
    case 'services':
        require 'services.php';
        break;
        
    case 'brands':
        require 'brands.php';
        break;
        
    case 'areas':
        require 'areas.php';
        break;
        
    case 'contact':
        require 'contact.php';
        break;
        
    case 'about':
        require 'about.php';
        break;
        
    case 'stats':
        $type = $segments[1] ?? 'public';
        $_GET['type'] = $type;
        require 'stats.php';
        break;
        
    case 'upload-image':
        require 'upload.php';
        break;
        
    default:
        // API info
        jsonResponse([
            'name' => 'RH Elektronik API',
            'version' => '2.0.0-php',
            'endpoints' => [
                'POST /api/admin/login',
                'GET /api/admin/stats',
                'GET|POST|PUT|DELETE /api/blog',
                'GET|POST|PUT|DELETE /api/products',
                'GET|POST|PUT|DELETE /api/services',
                'GET|POST|PUT|DELETE /api/brands',
                'GET|POST|PUT|DELETE /api/areas',
                'GET|PUT /api/contact',
                'GET|POST|PUT|DELETE /api/about',
                'GET /api/stats/public',
                'POST /api/upload-image'
            ]
        ]);
}
