<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/_bootstrap.php';

golder_require_method('POST');
$ctx = golder_api_auth('desktop_sync');
$customer = sync_api_require_profile_sync_customer((int)($ctx['customer_id'] ?? 0));
$input = golder_api_input();
$localProfiles = $input['local_profiles'] ?? [];
if (!is_array($localProfiles)) {
    $localProfiles = [];
}

try {
    $tenant = golder_tenant_pdo_from_customer($customer);
    $updatedAtExpr = sync_api_table_has_column($tenant, 'profiles', 'updated_at')
        ? 'COALESCE(updated_at, created_at, UTC_TIMESTAMP())'
        : 'COALESCE(created_at, UTC_TIMESTAMP())';

    $remoteRows = $tenant->query(
        "SELECT id, name, {$updatedAtExpr} AS updated_at, COALESCE(is_deleted, 0) AS is_deleted
         FROM profiles"
    )->fetchAll() ?: [];

    $remoteMap = [];
    foreach ($remoteRows as $row) {
        $id = trim((string)($row['id'] ?? ''));
        if ($id === '') {
            continue;
        }
        $remoteMap[$id] = [
            'id' => $id,
            'name' => (string)($row['name'] ?? ''),
            'updated_at' => (string)($row['updated_at'] ?? ''),
            'is_deleted' => (int)($row['is_deleted'] ?? 0),
        ];
    }

    $localMap = [];
    foreach ($localProfiles as $item) {
        if (!is_array($item)) {
            continue;
        }
        $id = trim((string)($item['id'] ?? ''));
        if ($id === '') {
            continue;
        }
        $localMap[$id] = [
            'id' => $id,
            'name' => (string)($item['name'] ?? ''),
            'updated_at' => trim((string)($item['updated_at'] ?? '')),
            'is_deleted' => (int)($item['is_deleted'] ?? 0),
        ];
    }

    $remoteOnly = [];
    $localOnly = [];
    $conflicts = [];

    foreach ($remoteMap as $id => $row) {
        if (!isset($localMap[$id])) {
            $remoteOnly[] = $row;
            continue;
        }
        $remoteTs = strtotime((string)$row['updated_at']) ?: 0;
        $localTs = strtotime((string)$localMap[$id]['updated_at']) ?: 0;
        if ($remoteTs !== $localTs) {
            $winner = ($remoteTs >= $localTs) ? 'remote' : 'local';
            $conflicts[] = [
                'id' => $id,
                'remote_updated_at' => (string)$row['updated_at'],
                'local_updated_at' => (string)$localMap[$id]['updated_at'],
                'winner' => $winner,
            ];
        }
    }

    foreach ($localMap as $id => $row) {
        if (!isset($remoteMap[$id])) {
            $localOnly[] = $row;
            $tenant->prepare(
                'INSERT INTO profile_sync_jobs (profile_id, job_type, status, payload_json, created_at)
                 VALUES (:pid, :jt, :st, :pl, UTC_TIMESTAMP())'
            )->execute([
                ':pid' => $id,
                ':jt' => 'upload_missing_profile',
                ':st' => 'pending',
                ':pl' => json_encode($row, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            ]);
        }
    }

    golder_json_response([
        'status' => 'ok',
        'remote_only' => $remoteOnly,
        'local_only' => $localOnly,
        'conflicts' => $conflicts,
    ]);
} catch (Throwable $e) {
    sync_api_fail_from_exception($e, 'PROFILE_RECONCILE_FAILED');
}


