<?php
require_once __DIR__ . '/config.php';

$path = isset($_GET['path']) && trim((string)$_GET['path']) !== ''
    ? trim((string)$_GET['path'])
    : LALAMOVE_JSON_PATH;

if (!file_exists($path)) {
    json_response(['ok' => false, 'error' => 'JSON file not found', 'path' => $path], 404);
}

$raw = file_get_contents($path);
$data = json_decode((string)$raw, true);

if (!is_array($data)) {
    json_response(['ok' => false, 'error' => 'Invalid JSON file'], 400);
}

$lalamoveOrderId = trim((string)($data['order_id'] ?? ''));
if ($lalamoveOrderId === '') {
    json_response(['ok' => false, 'error' => 'order_id missing'], 400);
}

$recipientName = trim((string)($data['recipient_name'] ?? ''));
$recipientPhoneRaw = trim((string)($data['recipient_phone'] ?? ''));
$recipientPhoneNorm = normalize_phone($recipientPhoneRaw);
$destinationShort = trim((string)($data['destination_short'] ?? ''));
$destinationFull = trim((string)($data['destination_full'] ?? ''));
$shareLink = trim((string)($data['share_link'] ?? ''));
$shareLinkFound = $shareLink !== '' ? 1 : 0;
$rawJson = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

$mysqli = db();

// scrape_runs start
$runStmt = $mysqli->prepare("
    INSERT INTO scrape_runs (source_name, run_status, output_json_path, started_at)
    VALUES ('lalamove_records', 'started', ?, NOW())
");
$runStmt->bind_param('s', $path);
$runStmt->execute();
$scrapeRunId = (int)$runStmt->insert_id;
$runStmt->close();

$stmt = $mysqli->prepare("
    INSERT INTO lalamove_orders (
        lalamove_order_id, status, recipient_name, recipient_phone_raw, recipient_phone_normalized,
        destination_short, destination_full, share_link, share_link_found, raw_json,
        scrape_status, first_seen_at, last_seen_at
    ) VALUES (
        ?, 'Completed', ?, ?, ?, ?, ?, ?, ?, ?, 'completed', NOW(), NOW()
    )
    ON DUPLICATE KEY UPDATE
        status = VALUES(status),
        recipient_name = VALUES(recipient_name),
        recipient_phone_raw = VALUES(recipient_phone_raw),
        recipient_phone_normalized = VALUES(recipient_phone_normalized),
        destination_short = VALUES(destination_short),
        destination_full = VALUES(destination_full),
        share_link = CASE
            WHEN VALUES(share_link) <> '' THEN VALUES(share_link)
            ELSE share_link
        END,
        share_link_found = CASE
            WHEN VALUES(share_link_found) = 1 THEN 1
            ELSE share_link_found
        END,
        raw_json = VALUES(raw_json),
        last_seen_at = NOW(),
        updated_at = NOW()
");

if (!$stmt) {
    $mysqli->query("UPDATE scrape_runs SET run_status='failed', error_message='" . $mysqli->real_escape_string($mysqli->error) . "', finished_at=NOW() WHERE id=" . $scrapeRunId);
    json_response(['ok' => false, 'error' => $mysqli->error], 500);
}

$stmt->bind_param(
    'sssssssis',
    $lalamoveOrderId, $recipientName, $recipientPhoneRaw, $recipientPhoneNorm,
    $destinationShort, $destinationFull, $shareLink, $shareLinkFound, $rawJson
);

if (!$stmt->execute()) {
    $err = $stmt->error;
    $stmt->close();
    $mysqli->query("UPDATE scrape_runs SET run_status='failed', error_message='" . $mysqli->real_escape_string($err) . "', finished_at=NOW() WHERE id=" . $scrapeRunId);
    json_response(['ok' => false, 'error' => $err], 500);
}
$stmt->close();

$rowId = 0;
$stmt = $mysqli->prepare("SELECT id FROM lalamove_orders WHERE lalamove_order_id = ?");
$stmt->bind_param('s', $lalamoveOrderId);
$stmt->execute();
$stmt->bind_result($rowId);
$stmt->fetch();
$stmt->close();

$mysqli->query("UPDATE scrape_runs SET run_status='success', records_found=1, records_updated=1, finished_at=NOW() WHERE id=" . $scrapeRunId);

json_response([
    'ok' => true,
    'message' => 'Lalamove JSON imported',
    'local_row_id' => $rowId,
    'lalamove_order_id' => $lalamoveOrderId,
    'recipient_phone_normalized' => $recipientPhoneNorm,
    'share_link_found' => (bool)$shareLinkFound
]);
