<?php
/**
 * EdumacFlo Synchronization Hub
 * Sync offline database changes to the online web portal
 */

// Function to safely push data to remote
function pushData($connection, $table, $url, $apiKey) {
    // Verify table exists
    $table_check = mysqli_query($connection, "SHOW TABLES LIKE '$table'");
    if (!$table_check || mysqli_num_rows($table_check) == 0) {
        return ["status" => "info", "message" => "Table '$table' not present in local database (skipped)"];
    }

    // Verify is_synced column exists
    $col_check = mysqli_query($connection, "SHOW COLUMNS FROM `$table` LIKE 'is_synced'");
    if (!$col_check || mysqli_num_rows($col_check) == 0) {
        @mysqli_query($connection, "ALTER TABLE `$table` ADD COLUMN `is_synced` TINYINT(1) DEFAULT 0");
    }

    $q = "SELECT * FROM `$table` WHERE `is_synced` = 0 LIMIT 500";
    $result = mysqli_query($connection, $q);
    $rows = [];
    $ids = [];
    if ($result) {
        while ($row = mysqli_fetch_assoc($result)) {
            $rows[] = $row;
            if (isset($row['id'])) {
                $ids[] = $row['id'];
            }
        }
    }

    if (empty($rows)) {
        return ["status" => "info", "message" => "No pending unsynced records for $table"];
    }

    $data = json_encode(["api_key" => $apiKey, "table" => $table, "data" => $rows]);
    
    $endpoint = rtrim($url, '/') . "/sync_receiver.php";
    $ch = curl_init($endpoint);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_err = curl_error($ch);
    curl_close($ch);

    if ($httpCode == 200) {
        $res = json_decode($response, true);
        if ($res && isset($res['status']) && $res['status'] == 'success') {
            if (!empty($ids)) {
                $id_list = implode(',', array_map('intval', $ids));
                mysqli_query($connection, "UPDATE `$table` SET `is_synced` = 1 WHERE `id` IN ($id_list)");
            }
            return ["status" => "success", "message" => "Successfully synced " . count($rows) . " records for table '$table'"];
        }
    }
    
    $err_detail = !empty($curl_err) ? " ($curl_err)" : "";
    return ["status" => "danger", "message" => "Failed to sync $table: HTTP $httpCode$err_detail"];
}

// Ensure remote_sync_url and sync_api_key columns exist in administratives
$chk_url = mysqli_query($connection, "SHOW COLUMNS FROM `administratives` LIKE 'remote_sync_url'");
if ($chk_url && mysqli_num_rows($chk_url) == 0) {
    @mysqli_query($connection, "ALTER TABLE `administratives` ADD COLUMN `remote_sync_url` VARCHAR(255) DEFAULT ''");
}
$chk_key = mysqli_query($connection, "SHOW COLUMNS FROM `administratives` LIKE 'sync_api_key'");
if ($chk_key && mysqli_num_rows($chk_key) == 0) {
    @mysqli_query($connection, "ALTER TABLE `administratives` ADD COLUMN `sync_api_key` VARCHAR(100) DEFAULT ''");
}

// Handle Sync Request
if (isset($_POST['run_sync'])) {
    $sync_url = trim($_POST['remote_sync_url'] ?? '');
    $sync_key = trim($_POST['sync_api_key'] ?? '');
    
    // Save settings
    $sync_url_esc = mysqli_real_escape_string($connection, $sync_url);
    $sync_key_esc = mysqli_real_escape_string($connection, $sync_key);
    mysqli_query($connection, "UPDATE `administratives` SET `remote_sync_url` = '$sync_url_esc', `sync_api_key` = '$sync_key_esc'");
    
    $results = [];
    $sync_tables = ["results1", "students", "fee_payment", "student_attendance", "behavioral"];
    foreach ($sync_tables as $st) {
        $results[] = pushData($connection, $st, $sync_url, $sync_key);
    }
    
    $_SESSION['sync_results'] = $results;
    header("Location: sync_manager");
    exit();
}

// Fetch current settings
$settings = ['remote_sync_url' => '', 'sync_api_key' => ''];
$q = mysqli_query($connection, "SELECT `remote_sync_url`, `sync_api_key` FROM `administratives` LIMIT 1");
if ($q && mysqli_num_rows($q) > 0) {
    $settings = mysqli_fetch_assoc($q);
}
?>

<div class="page-title">
    <div>
        <h1><i class="fa fa-sync"></i> Synchronization Hub</h1>
        <p>Sync your local offline school records to the live cloud portal</p>
    </div>
</div>

<?php if (isset($_SESSION['sync_results'])): ?>
    <div class="row">
        <div class="col-md-12">
            <div class="alert alert-info alert-dismissible" style="border-radius:10px;">
                <button type="button" class="close" data-dismiss="alert">&times;</button>
                <h4 style="margin-top:0;"><i class="fa fa-info-circle"></i> Sync Operation Summary:</h4>
                <ul style="margin-bottom:0; padding-left:20px;">
                    <?php foreach ($_SESSION['sync_results'] as $r): ?>
                        <li class="text-<?= $r['status'] ?>" style="font-weight:600; margin:4px 0;"><?= htmlspecialchars($r['message']) ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </div>
    </div>
    <?php unset($_SESSION['sync_results']); ?>
<?php endif; ?>

<div class="row">
    <div class="col-md-6">
        <div class="card p-4" style="border-radius:12px; box-shadow:0 2px 10px rgba(0,0,0,0.05);">
            <h4 style="font-weight:700; color:#2c3e50;"><i class="fa fa-cogs text-primary"></i> Cloud Sync Configuration</h4>
            <hr>
            <form method="POST" action="">
                <div class="form-group">
                    <label><b>Remote Cloud Server URL:</b></label>
                    <input type="url" name="remote_sync_url" class="form-control input-lg" value="<?= htmlspecialchars($settings['remote_sync_url'] ?? '') ?>" placeholder="https://your-live-school-portal.com" required>
                    <p class="help-block small text-muted">The online URL where the centralized EdumacFlo database is hosted.</p>
                </div>
                <div class="form-group">
                    <label><b>Sync API Security Key:</b></label>
                    <input type="password" name="sync_api_key" class="form-control input-lg" value="<?= htmlspecialchars($settings['sync_api_key'] ?? '') ?>" placeholder="Enter API sync secret key" required>
                    <p class="help-block small text-muted">Shared secret token used to authenticate synchronization packets.</p>
                </div>
                <button type="submit" name="run_sync" class="btn btn-primary btn-block btn-lg" style="font-weight:700; border-radius:8px; margin-top:20px;">
                    <i class="fa fa-cloud-upload-alt"></i> Start Synchronization Now
                </button>
            </form>
        </div>
    </div>

    <div class="col-md-6">
        <div class="card p-4" style="border-radius:12px; box-shadow:0 2px 10px rgba(0,0,0,0.05);">
            <h4 style="font-weight:700; color:#2c3e50;"><i class="fa fa-shield-alt text-success"></i> Sync Architecture</h4>
            <hr>
            <p>Your <strong>EdumacFlo</strong> instance is equipped with hybrid offline/online synchronization:</p>
            <ul style="line-height:1.8;">
                <li><strong>Local First:</strong> Record continuous assessments, attendance, exams, and payments locally without internet interruptions.</li>
                <li><strong>Safe Push:</strong> When internet is connected, click <em>Start Synchronization Now</em> to push unsynced records.</li>
                <li><strong>Data Covered:</strong> Student profiles, terminal results, payments, attendance logs, and student conduct.</li>
                <li><strong>Duplicate Protection:</strong> Each record tracks its sync state (<code>is_synced</code>) to prevent double writes.</li>
            </ul>
        </div>
    </div>
</div>
