<?php
/**
 * Check SQLite Sync Status
 * API untuk mengecek status sinkronisasi SQLite
 */

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

$sqlite_path = 'data/sipp_sync.sqlite';

try {
    if (!file_exists($sqlite_path)) {
        echo json_encode([
            'status' => 'not_synced',
            'message' => 'Belum pernah sinkronisasi',
            'total_records' => 0,
            'last_sync' => null
        ]);
        exit;
    }
    
    $sqlite_pdo = new PDO("sqlite:$sqlite_path", null, null, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
    
    // Get total records
    $stmt = $sqlite_pdo->query("SELECT COUNT(*) as total FROM arsip");
    $total_records = $stmt->fetch()['total'];
    
    // Get last sync info
    $stmt = $sqlite_pdo->query("SELECT * FROM sync_log ORDER BY sync_date DESC LIMIT 1");
    $last_sync = $stmt->fetch();
    
    if (!$last_sync) {
        echo json_encode([
            'status' => 'unknown',
            'message' => 'Status sinkronisasi tidak diketahui',
            'total_records' => $total_records,
            'last_sync' => null
        ]);
        exit;
    }
    
    // Determine status based on last sync date
    $last_sync_time = strtotime($last_sync['sync_date']);
    $current_time = time();
    $hours_diff = ($current_time - $last_sync_time) / 3600;
    
    if ($hours_diff > 72) { // More than 3 days
        $status = 'outdated';
        $message = 'Data mungkin sudah usang (>3 hari)';
    } elseif ($hours_diff > 24) { // More than 1 day
        $status = 'old';
        $message = 'Data agak lama (>1 hari)';
    } else {
        $status = 'fresh';
        $message = 'Data masih fresh';
    }
    
    echo json_encode([
        'status' => $status,
        'message' => $message,
        'total_records' => $total_records,
        'last_sync' => $last_sync['sync_date'],
        'hours_since_sync' => round($hours_diff, 1),
        'sync_status' => $last_sync['status']
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Error: ' . $e->getMessage(),
        'total_records' => 0,
        'last_sync' => null
    ]);
}
?>
