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

header('Content-Type: application/json; charset=utf-8');

function office_agent_json(array $data, int $status = 200): void
{
    http_response_code($status);
    echo json_encode($data, JSON_UNESCAPED_SLASHES);
    exit;
}

$mysqli = db();

$agentName = trim((string)($_GET['agent_name'] ?? 'office-pc-1'));
if ($agentName === '') {
    $agentName = 'office-pc-1';
}

$givenKey = (string)($_GET['key'] ?? '');
if (defined('OFFICE_AGENT_KEY') && OFFICE_AGENT_KEY !== '') {
    if ($givenKey === '' || !hash_equals(OFFICE_AGENT_KEY, $givenKey)) {
        office_agent_json([
            'ok' => false,
            'error' => 'forbidden'
        ], 403);
    }
}

$officeIp  = (string)($_SERVER['REMOTE_ADDR'] ?? '');
$userAgent = substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 255);

/*
 * Match the REAL schema already in your table:
 * - agent_name
 * - last_public_ip
 * - last_seen_at
 * - last_poll_at
 * - last_user_agent
 * - is_online
 * - created_at
 * - updated_at
 */

$update = $mysqli->prepare("
    UPDATE office_agent_status
    SET last_public_ip = ?,
        last_seen_at = NOW(),
        last_poll_at = NOW(),
        last_user_agent = ?,
        is_online = 1,
        updated_at = NOW()
    WHERE agent_name = ?
");

if (!$update) {
    office_agent_json([
        'ok' => false,
        'error' => 'prepare update failed',
        'mysql_error' => $mysqli->error
    ], 500);
}

$update->bind_param('sss', $officeIp, $userAgent, $agentName);
$update->execute();

if ($update->affected_rows < 1) {
    $update->close();

    $insert = $mysqli->prepare("
        INSERT INTO office_agent_status
        (agent_name, last_public_ip, last_seen_at, last_poll_at, last_user_agent, is_online, created_at, updated_at)
        VALUES (?, ?, NOW(), NOW(), ?, 1, NOW(), NOW())
    ");

    if (!$insert) {
        office_agent_json([
            'ok' => false,
            'error' => 'prepare insert failed',
            'mysql_error' => $mysqli->error
        ], 500);
    }

    $insert->bind_param('sss', $agentName, $officeIp, $userAgent);

    if (!$insert->execute()) {
        office_agent_json([
            'ok' => false,
            'error' => 'insert failed',
            'mysql_error' => $insert->error
        ], 500);
    }

    $insert->close();
} else {
    if (!$update->execute()) {
        office_agent_json([
            'ok' => false,
            'error' => 'update failed',
            'mysql_error' => $update->error
        ], 500);
    }
    $update->close();
}

$sql = "
SELECT COUNT(*) AS pending_count
FROM shopify_orders so
LEFT JOIN order_matches om
    ON om.shopify_order_row_id = so.id
WHERE so.match_status = 'unmatched'
  AND om.id IS NULL
  AND (so.financial_status IS NULL OR LOWER(so.financial_status) NOT IN ('voided', 'refunded'))
  AND so.order_created_at >= (NOW() - INTERVAL 1 DAY)
";

$res = $mysqli->query($sql);
$pendingCount = 0;
if ($res && ($row = $res->fetch_assoc())) {
    $pendingCount = (int)($row['pending_count'] ?? 0);
}

office_agent_json([
    'ok' => true,
    'agent_name' => $agentName,
    'office_ip' => $officeIp,
    'pending_count' => $pendingCount,
    'run_check' => ($pendingCount > 0)
]);