<?php
/**
 * API: Sync with Mobile App
 * Two-way synchronization for cases, remedies, and rubrics
 * Method: POST
 * Authentication: API Key or JWT Token
 */

require_once '../../config/config.php';
require_once '../../includes/functions.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-API-Key, X-Sync-Token');

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

// ============================================
// AUTHENTICATION
// ============================================

function authenticateAPI() {
    $headers = getallheaders();
    $apiKey = $headers['X-API-Key'] ?? $_SERVER['HTTP_X_API_KEY'] ?? '';
    
    if (empty($apiKey)) {
        http_response_code(401);
        echo json_encode(['success' => false, 'error' => 'API key required']);
        exit;
    }
    
    $pdo = getDB();
    $stmt = $pdo->prepare("SELECT id, full_name, email, last_sync FROM users WHERE api_key = ? AND role = 'doctor' AND is_active = 1");
    $stmt->execute([$apiKey]);
    $user = $stmt->fetch();
    
    if (!$user) {
        http_response_code(401);
        echo json_encode(['success' => false, 'error' => 'Invalid API key']);
        exit;
    }
    
    return $user;
}

// ============================================
// SYNC FUNCTIONS
// ============================================

function getLastSyncToken($userId, $pdo) {
    $stmt = $pdo->prepare("SELECT last_sync FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $result = $stmt->fetch();
    return $result['last_sync'] ?? date('Y-m-d H:i:s', strtotime('-30 days'));
}

function updateLastSync($userId, $pdo) {
    $stmt = $pdo->prepare("UPDATE users SET last_sync = NOW() WHERE id = ?");
    $stmt->execute([$userId]);
}

function getRemediesForSync($pdo, $lastSync) {
    $stmt = $pdo->prepare("SELECT id, name, abbreviation, materia_medica_text, clinical_indications, modalities, 
                          created_at, updated_at 
                          FROM remedies 
                          WHERE updated_at > ? OR created_at > ?
                          ORDER BY name");
    $stmt->execute([$lastSync, $lastSync]);
    return $stmt->fetchAll();
}

function getRubricsForSync($pdo, $lastSync) {
    $stmt = $pdo->prepare("SELECT id, parent_id, rubric_name, full_path, level, sort_order, chapter_name,
                          created_at, updated_at 
                          FROM rubrics 
                          WHERE updated_at > ? OR created_at > ?
                          ORDER BY full_path");
    $stmt->execute([$lastSync, $lastSync]);
    return $stmt->fetchAll();
}

function getRubricRemediesForSync($pdo, $lastSync) {
    $stmt = $pdo->prepare("SELECT rr.id, rr.rubric_id, rr.remedy_id, rr.grade, rr.created_at
                          FROM rubric_remedy rr
                          WHERE rr.created_at > ?");
    $stmt->execute([$lastSync]);
    return $stmt->fetchAll();
}

function processMobileChanges($userId, $changes, $pdo) {
    $results = [
        'created' => 0,
        'updated' => 0,
        'errors' => []
    ];
    
    // Process new cases from mobile
    if (!empty($changes['cases'])) {
        foreach ($changes['cases'] as $case) {
            try {
                // Check if case exists
                if (isset($case['id']) && $case['id'] > 0) {
                    $stmt = $pdo->prepare("SELECT id FROM cases WHERE id = ? AND user_id = ?");
                    $stmt->execute([$case['id'], $userId]);
                    if ($stmt->fetch()) {
                        // Update existing case
                        $stmt = $pdo->prepare("UPDATE cases SET 
                                              patient_name = ?, patient_mobile = ?, patient_age = ?,
                                              patient_gender = ?, chief_complaint = ?, case_history = ?,
                                              physical_generals = ?, mental_emotional = ?, modalities = ?,
                                              status = ?, follow_up_date = ?, updated_at = NOW()
                                              WHERE id = ? AND user_id = ?");
                        $stmt->execute([
                            $case['patient_name'], $case['patient_mobile'], $case['patient_age'] ?? null,
                            $case['patient_gender'] ?? null, $case['chief_complaint'] ?? '',
                            $case['case_history'] ?? '', $case['physical_generals'] ?? '',
                            $case['mental_emotional'] ?? '', $case['modalities'] ?? '',
                            $case['status'] ?? 'active', $case['follow_up_date'] ?? null,
                            $case['id'], $userId
                        ]);
                        $results['updated']++;
                    } else {
                        // Create new case
                        $stmt = $pdo->prepare("INSERT INTO cases (user_id, patient_name, patient_mobile, patient_age,
                                              patient_gender, chief_complaint, case_history, physical_generals,
                                              mental_emotional, modalities, status, follow_up_date, created_at)
                                              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
                        $stmt->execute([
                            $userId, $case['patient_name'], $case['patient_mobile'], $case['patient_age'] ?? null,
                            $case['patient_gender'] ?? null, $case['chief_complaint'] ?? '',
                            $case['case_history'] ?? '', $case['physical_generals'] ?? '',
                            $case['mental_emotional'] ?? '', $case['modalities'] ?? '',
                            $case['status'] ?? 'active', $case['follow_up_date'] ?? null
                        ]);
                        $results['created']++;
                    }
                } else {
                    // Create new case
                    $stmt = $pdo->prepare("INSERT INTO cases (user_id, patient_name, patient_mobile, patient_age,
                                          patient_gender, chief_complaint, case_history, physical_generals,
                                          mental_emotional, modalities, status, follow_up_date, created_at)
                                          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
                    $stmt->execute([
                        $userId, $case['patient_name'], $case['patient_mobile'], $case['patient_age'] ?? null,
                        $case['patient_gender'] ?? null, $case['chief_complaint'] ?? '',
                        $case['case_history'] ?? '', $case['physical_generals'] ?? '',
                        $case['mental_emotional'] ?? '', $case['modalities'] ?? '',
                        $case['status'] ?? 'active', $case['follow_up_date'] ?? null
                    ]);
                    $results['created']++;
                }
            } catch (Exception $e) {
                $results['errors'][] = $e->getMessage();
            }
        }
    }
    
    return $results;
}

// ============================================
// MAIN PROCESSING
// ============================================

// Authenticate user
$user = authenticateAPI();
$userId = $user['id'];
$pdo = getDB();

// Get sync token (last sync time from client)
$headers = getallheaders();
$clientSyncToken = $headers['X-Sync-Token'] ?? $_SERVER['HTTP_X_SYNC_TOKEN'] ?? null;
$lastSync = $clientSyncToken ? date('Y-m-d H:i:s', strtotime($clientSyncToken)) : getLastSyncToken($userId, $pdo);

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    // Pull data from server
    $remedies = getRemediesForSync($pdo, $lastSync);
    $rubrics = getRubricsForSync($pdo, $lastSync);
    $rubricRemedies = getRubricRemediesForSync($pdo, $lastSync);
    
    // Get cases updated after last sync
    $stmt = $pdo->prepare("SELECT c.id, c.patient_name, c.patient_mobile, c.patient_age, c.patient_gender,
                          c.chief_complaint, c.case_history, c.physical_generals, c.mental_emotional,
                          c.modalities, c.selected_rubrics, c.repertorization_result, c.prescribed_remedy_id,
                          c.prescription_potency, c.created_at, c.updated_at, c.status, c.follow_up_date,
                          r.name as remedy_name
                          FROM cases c
                          LEFT JOIN remedies r ON c.prescribed_remedy_id = r.id
                          WHERE c.user_id = ? AND (c.updated_at > ? OR c.created_at > ?)
                          ORDER BY c.updated_at ASC");
    $stmt->execute([$userId, $lastSync, $lastSync]);
    $cases = $stmt->fetchAll();
    
    // Format remedies
    foreach ($remedies as &$remedy) {
        $remedy['modalities'] = json_decode($remedy['modalities'], true);
    }
    
    echo json_encode([
        'success' => true,
        'sync_type' => 'pull',
        'data' => [
            'remedies' => $remedies,
            'rubrics' => $rubrics,
            'rubric_remedies' => $rubricRemedies,
            'cases' => $cases
        ],
        'server_time' => date('Y-m-d H:i:s'),
        'next_sync_token' => date('Y-m-d H:i:s')
    ]);
    
} elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Push and pull data (two-way sync)
    $input = json_decode(file_get_contents('php://input'), true);
    
    $syncResults = ['pulled' => [], 'pushed' => []];
    
    // Process mobile changes
    if (!empty($input['changes'])) {
        $syncResults['pushed'] = processMobileChanges($userId, $input['changes'], $pdo);
    }
    
    // Get updated data after processing changes
    $newLastSync = $input['sync_token'] ?? $lastSync;
    $remedies = getRemediesForSync($pdo, $newLastSync);
    $rubrics = getRubricsForSync($pdo, $newLastSync);
    $rubricRemedies = getRubricRemediesForSync($pdo, $newLastSync);
    
    $stmt = $pdo->prepare("SELECT c.id, c.patient_name, c.patient_mobile, c.patient_age, c.patient_gender,
                          c.chief_complaint, c.case_history, c.physical_generals, c.mental_emotional,
                          c.modalities, c.selected_rubrics, c.repertorization_result, c.prescribed_remedy_id,
                          c.prescription_potency, c.created_at, c.updated_at, c.status, c.follow_up_date,
                          r.name as remedy_name
                          FROM cases c
                          LEFT JOIN remedies r ON c.prescribed_remedy_id = r.id
                          WHERE c.user_id = ? AND (c.updated_at > ? OR c.created_at > ?)
                          ORDER BY c.updated_at ASC");
    $stmt->execute([$userId, $newLastSync, $newLastSync]);
    $cases = $stmt->fetchAll();
    
    foreach ($remedies as &$remedy) {
        $remedy['modalities'] = json_decode($remedy['modalities'], true);
    }
    
    // Update user's last sync time
    updateLastSync($userId, $pdo);
    
    echo json_encode([
        'success' => true,
        'sync_type' => 'two-way',
        'results' => $syncResults,
        'data' => [
            'remedies' => $remedies,
            'rubrics' => $rubrics,
            'rubric_remedies' => $rubricRemedies,
            'cases' => $cases
        ],
        'server_time' => date('Y-m-d H:i:s'),
        'next_sync_token' => date('Y-m-d H:i:s')
    ]);
    
} else {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
}
?>