<?php
/**
 * ZLO Platform - API Entry Point
 * RESTful API Router
 */

declare(strict_types=1);

// Error reporting
error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');

// CORS headers
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-CSRF-Token, X-Requested-With');
header('Access-Control-Allow-Credentials: true');

// Handle preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

// Load required files
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/core/Security.php';
require_once __DIR__ . '/core/Router.php';
require_once __DIR__ . '/core/Model.php';
require_once __DIR__ . '/core/Mailer.php';

// Load controllers
require_once __DIR__ . '/controllers/AuthController.php';
require_once __DIR__ . '/controllers/SolutionController.php';
require_once __DIR__ . '/controllers/BlogController.php';
require_once __DIR__ . '/controllers/LeadController.php';
require_once __DIR__ . '/controllers/ContactController.php';
require_once __DIR__ . '/controllers/UploadController.php';
require_once __DIR__ . '/controllers/PageController.php';
require_once __DIR__ . '/controllers/SettingController.php';
require_once __DIR__ . '/controllers/SearchController.php';
require_once __DIR__ . '/controllers/NewsletterController.php';
require_once __DIR__ . '/controllers/CaseStudyController.php';
require_once __DIR__ . '/controllers/AnalyticsController.php';

// Initialize router
$router = new Router();

// =====================================================
// PUBLIC ROUTES
// =====================================================

// Health check
$router->get('health', function() {
    return [
        'status' => 'healthy',
        'version' => '1.0.0',
        'timestamp' => date('Y-m-d H:i:s')
    ];
});

// Authentication
$router->post('auth/login', [AuthController::class, 'login']);
$router->post('auth/logout', [AuthController::class, 'logout']);
$router->post('auth/refresh', [AuthController::class, 'refresh']);

// Solutions (public)
$router->get('solutions', [SolutionController::class, 'index']);
$router->get('solutions/featured', [SolutionController::class, 'featured']);
$router->get('solutions/stats', [SolutionController::class, 'stats']);
$router->get('solutions/{id}', [SolutionController::class, 'show']);
$router->get('solutions/slug/{slug}', [SolutionController::class, 'bySlug']);

// Blog (public)
$router->get('blog/posts', [BlogController::class, 'index']);
$router->get('blog/posts/{slug}', [BlogController::class, 'show']);
$router->get('blog/categories', [BlogController::class, 'categories']);

// Case Studies (public)
$router->get('case-studies', [CaseStudyController::class, 'index']);
$router->get('case-studies/featured', [CaseStudyController::class, 'featured']);
$router->get('case-studies/industries', [CaseStudyController::class, 'industries']);
$router->get('case-studies/{slug}', [CaseStudyController::class, 'show']);

// Analytics (public - tracking)
$router->post('analytics/track', [AnalyticsController::class, 'track']);

// Leads (public - for form submissions)
$router->post('leads', [LeadController::class, 'create']);

// Contact (public)
$router->post('contact/submit', [ContactController::class, 'submit']);

// Newsletter (public)
$router->post('newsletter/subscribe', [NewsletterController::class, 'subscribe']);
$router->post('newsletter/unsubscribe', [NewsletterController::class, 'unsubscribe']);

// Search (public)
$router->get('search', [SearchController::class, 'search']);
$router->get('search/suggestions', [SearchController::class, 'suggestions']);
$router->get('search/popular', [SearchController::class, 'popular']);

// Pages (public)
$router->get('pages', [PageController::class, 'index']);
$router->get('pages/slug/{slug}', [PageController::class, 'bySlug']);
$router->get('pages/menu', [PageController::class, 'menu']);

// Settings (public)
$router->get('settings/public', [SettingController::class, 'public']);
$router->get('settings/seo', [SettingController::class, 'seo']);
$router->get('settings/contact', [SettingController::class, 'contact']);
$router->get('settings/social', [SettingController::class, 'social']);

// =====================================================
// PROTECTED ROUTES (Require Authentication)
// =====================================================

$router->group('api', function($router) {
    
    // Current user
    $router->get('me', [AuthController::class, 'me']);
    $router->post('change-password', [AuthController::class, 'changePassword']);
    
    // Solutions (admin)
    $router->post('solutions', [SolutionController::class, 'create']);
    $router->put('solutions/{id}', [SolutionController::class, 'update']);
    $router->patch('solutions/{id}', [SolutionController::class, 'update']);
    $router->delete('solutions/{id}', [SolutionController::class, 'delete']);
    
    // Blog (admin)
    $router->post('blog/posts', [BlogController::class, 'create']);
    $router->put('blog/posts/{id}', [BlogController::class, 'update']);
    $router->patch('blog/posts/{id}', [BlogController::class, 'update']);
    $router->delete('blog/posts/{id}', [BlogController::class, 'delete']);
    
    // Leads (admin)
    $router->get('leads', [LeadController::class, 'index']);
    $router->get('leads/{id}', [LeadController::class, 'show']);
    $router->put('leads/{id}', [LeadController::class, 'update']);
    $router->patch('leads/{id}', [LeadController::class, 'update']);
    $router->delete('leads/{id}', [LeadController::class, 'delete']);
    $router->post('leads/{id}/assign', [LeadController::class, 'assign']);
    $router->post('leads/{id}/status', [LeadController::class, 'updateStatus']);
    $router->get('leads/stats', [LeadController::class, 'stats']);
    $router->get('leads/search', [LeadController::class, 'search']);
    
    // Contact messages (admin)
    $router->get('contact/messages', [ContactController::class, 'index']);
    $router->get('contact/messages/{id}', [ContactController::class, 'show']);
    $router->post('contact/messages/{id}/status', [ContactController::class, 'updateStatus']);
    $router->delete('contact/messages/{id}', [ContactController::class, 'delete']);
    $router->get('contact/stats', [ContactController::class, 'stats']);
    
    // Uploads (admin)
    $router->get('uploads', [UploadController::class, 'index']);
    $router->post('uploads', [UploadController::class, 'upload']);
    $router->delete('uploads/{id}', [UploadController::class, 'delete']);
    
    // Pages (admin)
    $router->get('pages/all', [PageController::class, 'index']);
    $router->get('pages/{id}', [PageController::class, 'show']);
    $router->post('pages', [PageController::class, 'create']);
    $router->put('pages/{id}', [PageController::class, 'update']);
    $router->patch('pages/{id}', [PageController::class, 'update']);
    $router->delete('pages/{id}', [PageController::class, 'delete']);
    $router->get('pages/templates/list', [PageController::class, 'templates']);
    
    // Settings (admin)
    $router->get('settings', [SettingController::class, 'index']);
    $router->put('settings', [SettingController::class, 'update']);
    $router->patch('settings', [SettingController::class, 'update']);
    $router->get('settings/tracking', [SettingController::class, 'tracking']);
    $router->post('settings/maintenance', [SettingController::class, 'toggleMaintenance']);
    
    // Newsletter (admin)
    $router->get('newsletter/subscribers', [NewsletterController::class, 'index']);
    $router->get('newsletter/stats', [NewsletterController::class, 'stats']);
    $router->get('newsletter/growth', [NewsletterController::class, 'growth']);
    $router->delete('newsletter/subscribers/{id}', [NewsletterController::class, 'delete']);
    $router->post('newsletter/import', [NewsletterController::class, 'import']);
    $router->get('newsletter/export', [NewsletterController::class, 'export']);
    
    // Case Studies (admin)
    $router->get('case-studies/all', [CaseStudyController::class, 'index']);
    $router->post('case-studies', [CaseStudyController::class, 'create']);
    $router->put('case-studies/{id}', [CaseStudyController::class, 'update']);
    $router->patch('case-studies/{id}', [CaseStudyController::class, 'update']);
    $router->delete('case-studies/{id}', [CaseStudyController::class, 'delete']);
    
    // Analytics (admin)
    $router->get('analytics/dashboard', [AnalyticsController::class, 'dashboard']);
    $router->get('analytics/traffic', [AnalyticsController::class, 'traffic']);
    $router->get('analytics/realtime', [AnalyticsController::class, 'realtime']);
    
    // Dashboard stats
    $router->get('dashboard/stats', function() {
        $db = new Database();
        
        // Get various stats
        $leadsCount = $db->fetchOne("SELECT COUNT(*) as count FROM leads")['count'];
        $newLeads = $db->fetchOne("SELECT COUNT(*) as count FROM leads WHERE status = 'new'")['count'];
        $blogPosts = $db->fetchOne("SELECT COUNT(*) as count FROM blog_posts WHERE status = 'published'")['count'];
        $contactMessages = $db->fetchOne("SELECT COUNT(*) as count FROM contact_messages WHERE status = 'new'")['count'];
        
        // Pipeline value
        $pipelineResult = $db->fetchOne("SELECT SUM(value_estimate) as total FROM sales_pipeline WHERE stage NOT IN ('won', 'lost')");
        $pipelineValue = $pipelineResult['total'] ?? 0;
        
        return [
            'leads' => [
                'total' => (int) $leadsCount,
                'new' => (int) $newLeads
            ],
            'blog_posts' => (int) $blogPosts,
            'contact_messages' => (int) $contactMessages,
            'pipeline_value' => (float) $pipelineValue
        ];
    });
    
}, [function() {
    AuthController::requireAuth();
}]);

// =====================================================
// ERROR HANDLING
// =====================================================

// 404 handler
$router->add('*', '.*', function() {
    http_response_code(404);
    return ['error' => 'Endpoint not found'];
});

// Global exception handler
set_exception_handler(function($e) {
    error_log($e->getMessage());
    error_log($e->getTraceAsString());
    
    http_response_code(500);
    header('Content-Type: application/json');
    
    $config = require __DIR__ . '/config/config.php';
    
    $response = [
        'success' => false,
        'error' => [
            'code' => 500,
            'message' => 'Internal server error'
        ]
    ];
    
    if ($config['app']['debug']) {
        $response['error']['debug'] = [
            'message' => $e->getMessage(),
            'file' => $e->getFile(),
            'line' => $e->getLine(),
            'trace' => $e->getTrace()
        ];
    }
    
    echo json_encode($response);
    exit;
});

// Dispatch request
try {
    $router->dispatch();
} catch (Exception $e) {
    error_log($e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => [
            'code' => 500,
            'message' => 'Internal server error'
        ]
    ]);
}
