<?php
/**
 * Sync Status API Endpoint
 * Returns synchronization statistics and monitoring data
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

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

require_once 'db.php';

try {
    // Get database size
    $dbSizeQuery = $pdo->query("
        SELECT 
            ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) as size_mb
        FROM information_schema.TABLES 
        WHERE table_schema = '" . DB_NAME . "'
    ");
    $dbSize = $dbSizeQuery->fetch(PDO::FETCH_ASSOC);
    
    // Get table count and record counts
    $tablesQuery = $pdo->query("
        SELECT 
            table_name,
            table_rows
        FROM information_schema.TABLES 
        WHERE table_schema = '" . DB_NAME . "'
        ORDER BY table_rows DESC
    ");
    $tables = $tablesQuery->fetchAll(PDO::FETCH_ASSOC);
    
    $totalRecords = array_sum(array_column($tables, 'table_rows'));
    
    // Count files in uploads directory
    $uploadsPath = dirname(__DIR__) . '/uploads';
    $fileCount = 0;
    $totalFileSize = 0;
    
    if (is_dir($uploadsPath)) {
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($uploadsPath, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::SELF_FIRST
        );
        
        foreach ($files as $file) {
            if ($file->isFile()) {
                $fileCount++;
                $totalFileSize += $file->getSize();
            }
        }
    }
    
    $totalFileSizeMB = round($totalFileSize / 1024 / 1024, 2);
    
    // Get sync logs (last 10 and statistics)
    $syncLogsExist = false;
    $syncLogs = [];
    $syncStats = [
        'total' => 0,
        'success' => 0,
        'failed' => 0,
        'success_rate' => 0,
        'last_sync' => null,
        'avg_duration' => 0
    ];
    
    // Check if sync_logs table exists
    $tableCheck = $pdo->query("SHOW TABLES LIKE 'sync_logs'");
    if ($tableCheck->rowCount() > 0) {
        $syncLogsExist = true;
        
        // Get last 10 sync operations
        $logsQuery = $pdo->query("
            SELECT * FROM sync_logs 
            ORDER BY created_at DESC 
            LIMIT 10
        ");
        $syncLogs = $logsQuery->fetchAll(PDO::FETCH_ASSOC);
        
        // Get sync statistics
        $statsQuery = $pdo->query("
            SELECT 
                COUNT(*) as total,
                SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) as success,
                SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed,
                AVG(duration_seconds) as avg_duration,
                MAX(CASE WHEN status = 'success' THEN created_at ELSE NULL END) as last_sync
            FROM sync_logs
            WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
        ");
        $stats = $statsQuery->fetch(PDO::FETCH_ASSOC);
        
        $syncStats = [
            'total' => (int)$stats['total'],
            'success' => (int)$stats['success'],
            'failed' => (int)$stats['failed'],
            'success_rate' => $stats['total'] > 0 ? round(($stats['success'] / $stats['total']) * 100, 1) : 0,
            'last_sync' => $stats['last_sync'],
            'avg_duration' => round($stats['avg_duration'] ?? 0, 1)
        ];
        
        // Get last 7 days history for chart
        $historyQuery = $pdo->query("
            SELECT 
                DATE(created_at) as date,
                COUNT(*) as count,
                AVG(duration_seconds) as avg_duration,
                AVG(backup_size_mb) as avg_size,
                SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) as success_count
            FROM sync_logs
            WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
            GROUP BY DATE(created_at)
            ORDER BY date ASC
        ");
        $syncStats['history'] = $historyQuery->fetchAll(PDO::FETCH_ASSOC);
    }
    
    // Helper function to check server health
    function checkServerHealth($url) {
        if (empty($url)) {
            return [
                'status' => 'not_configured',
                'response_time' => null,
                'server' => 'غير مُعدّ'
            ];
        }
        
        $startTime = microtime(true);
        $ch = curl_init();
        
        // Test with health.php endpoint
        $testUrl = rtrim($url, '/') . '/health.php';
        
        curl_setopt($ch, CURLOPT_URL, $testUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);
        
        $endTime = microtime(true);
        $responseTime = round(($endTime - $startTime) * 1000); // Convert to milliseconds
        
        if ($httpCode === 200 && $response !== false) {
            return [
                'status' => 'online',
                'response_time' => $responseTime,
                'server' => parse_url($url, PHP_URL_HOST)
            ];
        } else {
            return [
                'status' => 'offline',
                'response_time' => $responseTime,
                'server' => parse_url($url, PHP_URL_HOST),
                'error' => $curlError ?: 'HTTP ' . $httpCode
            ];
        }
    }
    
    // Server health check
    $primaryHealth = [
        'status' => 'online',
        'response_time' => 0,
        'server' => $_SERVER['HTTP_HOST'] ?? 'localhost'
    ];
    
    // Check secondary server if URL provided
    $secondaryUrl = $_GET['secondary_url'] ?? '';
    $secondaryHealth = checkServerHealth($secondaryUrl);
    
    // Response
    echo json_encode([
        'success' => true,
        'data' => [
            'database' => [
                'size_mb' => (float)$dbSize['size_mb'],
                'table_count' => count($tables),
                'total_records' => $totalRecords,
                'tables' => $tables
            ],
            'files' => [
                'count' => $fileCount,
                'total_size_mb' => $totalFileSizeMB
            ],
            'sync_logs_enabled' => $syncLogsExist,
            'sync_logs' => $syncLogs,
            'sync_stats' => $syncStats,
            'server_health' => [
                'primary' => $primaryHealth,
                'secondary' => $secondaryHealth
            ],
            'timestamp' => date('Y-m-d H:i:s')
        ]
    ], JSON_UNESCAPED_UNICODE);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'خطأ في جلب بيانات المزامنة: ' . $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}
