<?php
declare(strict_types=1);
session_start();

require_once __DIR__ . '/config.php';

/*
|--------------------------------------------------------------------------
| Basic hardcoded login
|--------------------------------------------------------------------------
| Username is hardcoded as requested.
| Password is stored as a PHP password_hash() bcrypt hash (PHP 7.2 suitable).
*/
const LALAMOVE_ADMIN_USERNAME = 'aaron@everestweb.com.my';
const LALAMOVE_ADMIN_PASSWORD_HASH = '$2y$12$DTdjY6.8HmkSleyAX4aD9OdGaddH.P4ncIjV95LY31qQzgK33ZdK.';
const LALAMOVE_ADMIN_SESSION_KEY = 'lalamove_admin_logged_in';
const LALAMOVE_ADMIN_USERNAME_SESSION_KEY = 'lalamove_admin_username';

const LALAMOVE_REMEMBER_COOKIE = 'lalamove_admin_remember';
const LALAMOVE_REMEMBER_DAYS = 180;

function h($value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function db_or_fail(): mysqli
{
    return db();
}

function is_https_request(): bool
{
    if (!empty($_SERVER['HTTPS']) && strtolower((string)$_SERVER['HTTPS']) !== 'off') {
        return true;
    }

    if (isset($_SERVER['SERVER_PORT']) && (int)$_SERVER['SERVER_PORT'] === 443) {
        return true;
    }

    if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower((string)$_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https') {
        return true;
    }

    return false;
}


function remember_cookie_expiry_timestamp(): int
{
    return time() + (LALAMOVE_REMEMBER_DAYS * 86400);
}

function build_remember_cookie_value(string $selector, string $validator): string
{
    return $selector . ':' . $validator;
}

function set_remember_cookie(string $selector, string $validator, int $expiresAt): bool
{
    $secure = is_https_request();
    $cookieValue = build_remember_cookie_value($selector, $validator);

    // PHP 7.2-compatible SameSite support
    return setcookie(
        LALAMOVE_REMEMBER_COOKIE,
        $cookieValue,
        $expiresAt,
        '/; samesite=Lax',
        '',
        $secure,
        true
    );
}

function clear_remember_cookie(): bool
{
    $secure = is_https_request();

    // PHP 7.2-compatible SameSite support
    return setcookie(
        LALAMOVE_REMEMBER_COOKIE,
        '',
        time() - 3600,
        '/; samesite=Lax',
        '',
        $secure,
        true
    );
}

function random_token_hex(int $bytes): string
{
    return bin2hex(random_bytes($bytes));
}

function current_user_agent(): string
{
    return substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 255);
}

function current_ip_address(): string
{
    $ip = (string)($_SERVER['REMOTE_ADDR'] ?? '');
    return substr($ip, 0, 45);
}

function hash_validator(string $validator): string
{
    return hash('sha256', $validator);
}

function is_logged_in(): bool
{
    return !empty($_SESSION[LALAMOVE_ADMIN_SESSION_KEY]);
}

function set_logged_in_session(string $username): void
{
    $_SESSION[LALAMOVE_ADMIN_SESSION_KEY] = 1;
    $_SESSION[LALAMOVE_ADMIN_USERNAME_SESSION_KEY] = $username;
    session_regenerate_id(true);
}

function clear_logged_in_session(): void
{
    unset($_SESSION[LALAMOVE_ADMIN_SESSION_KEY], $_SESSION[LALAMOVE_ADMIN_USERNAME_SESSION_KEY]);
    session_regenerate_id(true);
}

function create_remember_token(mysqli $mysqli, string $username): void
{
    $selector = random_token_hex(9);
    $validator = random_token_hex(32);
    $tokenHash = hash_validator($validator);
    $expiresAtTs = remember_cookie_expiry_timestamp();
    $expiresAtSql = date('Y-m-d H:i:s', $expiresAtTs);
    $deviceLabel = 'Saved device';
    $userAgent = current_user_agent();
    $ipAddress = current_ip_address();

    $stmt = $mysqli->prepare("
        INSERT INTO admin_remember_tokens
        (selector, token_hash, username, device_label, user_agent, ip_address, expires_at, last_used_at, created_at, updated_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW(), NOW())
    ");
    if (!$stmt) {
        return;
    }

    $stmt->bind_param(
        'sssssss',
        $selector,
        $tokenHash,
        $username,
        $deviceLabel,
        $userAgent,
        $ipAddress,
        $expiresAtSql
    );
    $stmt->execute();
    $stmt->close();

    set_remember_cookie($selector, $validator, $expiresAtTs);
}

function delete_remember_token_by_selector(mysqli $mysqli, string $selector): void
{
    $stmt = $mysqli->prepare("DELETE FROM admin_remember_tokens WHERE selector = ?");
    if (!$stmt) {
        return;
    }
    $stmt->bind_param('s', $selector);
    $stmt->execute();
    $stmt->close();
}

function delete_current_remember_token_from_cookie(mysqli $mysqli): void
{
    $cookie = (string)($_COOKIE[LALAMOVE_REMEMBER_COOKIE] ?? '');
    if ($cookie === '' || strpos($cookie, ':') === false) {
        clear_remember_cookie();
        return;
    }

    list($selector) = explode(':', $cookie, 2);
    $selector = trim((string)$selector);
    if ($selector !== '') {
        delete_remember_token_by_selector($mysqli, $selector);
    }

    clear_remember_cookie();
}

function try_auto_login_from_remember_cookie(mysqli $mysqli): bool
{
    if (is_logged_in()) {
        return true;
    }

    $cookie = (string)($_COOKIE[LALAMOVE_REMEMBER_COOKIE] ?? '');
    if ($cookie === '' || strpos($cookie, ':') === false) {
        return false;
    }

    list($selector, $validator) = explode(':', $cookie, 2);
    $selector = trim((string)$selector);
    $validator = trim((string)$validator);

    if ($selector === '' || $validator === '') {
        clear_remember_cookie();
        return false;
    }

    $stmt = $mysqli->prepare("
        SELECT id, username, token_hash, expires_at
        FROM admin_remember_tokens
        WHERE selector = ?
        LIMIT 1
    ");
    if (!$stmt) {
        return false;
    }

    $stmt->bind_param('s', $selector);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result ? $result->fetch_assoc() : null;
    $stmt->close();

    if (!$row) {
        clear_remember_cookie();
        return false;
    }

    $expiresAt = strtotime((string)$row['expires_at']);
    if ($expiresAt === false || $expiresAt < time()) {
        delete_remember_token_by_selector($mysqli, $selector);
        clear_remember_cookie();
        return false;
    }

    $expectedHash = (string)($row['token_hash'] ?? '');
    if (!hash_equals($expectedHash, hash_validator($validator))) {
        delete_remember_token_by_selector($mysqli, $selector);
        clear_remember_cookie();
        return false;
    }

    $username = (string)($row['username'] ?? '');
    if ($username === '' || !hash_equals(LALAMOVE_ADMIN_USERNAME, $username)) {
        delete_remember_token_by_selector($mysqli, $selector);
        clear_remember_cookie();
        return false;
    }

    set_logged_in_session($username);

    $newValidator = random_token_hex(32);
    $newTokenHash = hash_validator($newValidator);
    $newExpiresTs = remember_cookie_expiry_timestamp();
    $newExpiresSql = date('Y-m-d H:i:s', $newExpiresTs);
    $userAgent = current_user_agent();
    $ipAddress = current_ip_address();
    $tokenId = (int)($row['id'] ?? 0);

    $upd = $mysqli->prepare("
        UPDATE admin_remember_tokens
        SET token_hash = ?, expires_at = ?, last_used_at = NOW(), user_agent = ?, ip_address = ?, updated_at = NOW()
        WHERE id = ?
        LIMIT 1
    ");
    if ($upd) {
        $upd->bind_param('ssssi', $newTokenHash, $newExpiresSql, $userAgent, $ipAddress, $tokenId);
        $upd->execute();
        $upd->close();
    }

    set_remember_cookie($selector, $newValidator, $newExpiresTs);
    return true;
}

function require_login(): void
{
    if (is_logged_in()) {
        return;
    }

    try {
        $mysqli = db_or_fail();
        if (try_auto_login_from_remember_cookie($mysqli)) {
            return;
        }
    } catch (Throwable $e) {
        // Fall through to login page.
    }

    render_login_page();
    exit;
}

function redirect_self(): void
{
    header('Location: ' . basename(__FILE__));
    exit;
}

function fetch_one(mysqli $mysqli, string $sql): int
{
    $res = $mysqli->query($sql);
    if (!$res) {
        return 0;
    }
    $row = $res->fetch_assoc();
    return (int)($row['c'] ?? 0);
}

function fetch_rows(mysqli $mysqli, string $sql): array
{
    $rows = [];
    $res = $mysqli->query($sql);
    if (!$res) {
        return $rows;
    }
    while ($row = $res->fetch_assoc()) {
        $rows[] = $row;
    }
    return $rows;
}

function render_login_page(string $error = ''): void
{
    ?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Lalamove Shopify Admin</title>
  <style>
    body { margin:0; font-family: Arial, Helvetica, sans-serif; background:#f5f7fb; color:#1f2937; }
    .wrap { min-height:100vh; display:flex; align-items:center; justify-content:center; padding:24px; }
    .card { width:100%; max-width:420px; background:#fff; border:1px solid #e5e7eb; border-radius:14px; box-shadow:0 10px 30px rgba(0,0,0,.06); padding:24px; }
    h1 { font-size:24px; margin:0 0 6px; }
    .sub { color:#6b7280; margin:0 0 20px; }
    label { display:block; font-weight:600; margin:14px 0 6px; }
    input[type=email], input[type=password] {
      width:100%; box-sizing:border-box; padding:12px 14px; border:1px solid #d1d5db; border-radius:10px; font-size:14px;
    }
    .btn { margin-top:18px; width:100%; border:0; background:#111827; color:#fff; padding:12px 14px; border-radius:10px; font-size:15px; cursor:pointer; }
    .err { background:#fef2f2; color:#991b1b; border:1px solid #fecaca; padding:10px 12px; border-radius:10px; margin-bottom:14px; }
    .note { margin-top:12px; color:#6b7280; font-size:12px; }
  </style>
</head>
<body>
  <div class="wrap">
    <div class="card">
      <h1>Lalamove Shopify Admin</h1>
      <p class="sub">Status dashboard login</p>
      <?php if ($error !== ''): ?>
        <div class="err"><?php echo h($error); ?></div>
      <?php endif; ?>
      <form method="post" action="">
        <label for="username">Username</label>
        <input type="email" name="username" id="username" required autocomplete="username">
        <label for="password">Password</label>
        <input type="password" name="password" id="password" required autocomplete="current-password">
        <button class="btn" type="submit" name="login" value="1">Login</button>
      </form>
      
    </div>
  </div>
</body>
</html>
<?php
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login'])) {
    $username = trim((string)($_POST['username'] ?? ''));
    $password = (string)($_POST['password'] ?? '');

    if (
        hash_equals(LALAMOVE_ADMIN_USERNAME, $username) &&
        password_verify($password, LALAMOVE_ADMIN_PASSWORD_HASH)
    ) {
        $mysqli = db_or_fail();
        set_logged_in_session($username);
        create_remember_token($mysqli, $username);
        redirect_self();
    }

    render_login_page('Invalid username or password.');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['logout'])) {
    try {
        $mysqli = db_or_fail();
        delete_current_remember_token_from_cookie($mysqli);
    } catch (Throwable $e) {
        clear_remember_cookie();
    }

    clear_logged_in_session();
    redirect_self();
}

require_login();

$mysqli = db();

$counts = [
    'unmatched_24h' => fetch_one($mysqli, "
        SELECT COUNT(*) AS c
        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)
    "),
    'matched_waiting_tracking' => fetch_one($mysqli, "
        SELECT COUNT(*) AS c
        FROM order_matches om
        WHERE om.match_decision IN ('auto_matched','manual_matched')
          AND om.tracking_sent = 0
          AND om.share_link IS NOT NULL
          AND om.share_link <> ''
    "),
    'tracking_sent_24h' => fetch_one($mysqli, "
        SELECT COUNT(*) AS c
        FROM order_matches om
        WHERE om.tracking_sent = 1
          AND om.tracking_sent_at >= (NOW() - INTERVAL 1 DAY)
    "),
    'office_online_15m' => fetch_one($mysqli, "
        SELECT COUNT(*) AS c
        FROM office_agent_status
        WHERE last_seen_at >= (NOW() - INTERVAL 15 MINUTE)
          AND is_online = 1
    "),
];

$recentOrders = fetch_rows($mysqli, "
    SELECT
        so.id,
        so.shopify_name,
        so.match_status,
        so.financial_status,
        so.fulfillment_status,
        so.order_created_at,
        om.match_decision,
        om.address_score,
        om.phone_score,
        om.tracking_sent,
        om.tracking_sent_at,
        om.share_link,
        lo.lalamove_order_id
    FROM shopify_orders so
    LEFT JOIN order_matches om ON om.shopify_order_row_id = so.id
    LEFT JOIN lalamove_orders lo ON lo.id = om.lalamove_order_row_id
    WHERE so.order_created_at >= (NOW() - INTERVAL 3 DAY)
    ORDER BY so.order_created_at DESC, so.id DESC
    LIMIT 50
");

$officeAgents = fetch_rows($mysqli, "
    SELECT
        agent_name,
        last_public_ip,
        last_seen_at,
        last_poll_at,
        last_user_agent,
        is_online
    FROM office_agent_status
    ORDER BY updated_at DESC, id DESC
    LIMIT 10
");
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Lalamove Shopify Admin</title>
  <style>
    :root {
      --bg:#f4f6fa; --card:#ffffff; --line:#e5e7eb; --text:#111827; --muted:#6b7280;
      --green:#065f46; --greenbg:#ecfdf5; --amber:#92400e; --amberbg:#fffbeb; --blue:#1d4ed8; --bluebg:#eff6ff;
      --red:#991b1b; --redbg:#fef2f2;
    }
    * { box-sizing:border-box; }
    body { margin:0; font-family: Arial, Helvetica, sans-serif; background:var(--bg); color:var(--text); }
    .top { background:#111827; color:#fff; padding:16px 20px; }
    .top-inner { max-width:1280px; margin:0 auto; display:flex; align-items:center; justify-content:space-between; gap:12px; }
    .title { font-size:22px; font-weight:700; }
    .subtitle { font-size:13px; color:#cbd5e1; margin-top:4px; }
    .logout-form button {
      border:1px solid rgba(255,255,255,.25); background:transparent; color:#fff; border-radius:10px; padding:10px 14px; cursor:pointer;
    }
    .container { max-width:1280px; margin:0 auto; padding:20px; }
    .grid { display:grid; grid-template-columns:repeat(4, minmax(0,1fr)); gap:16px; margin-bottom:18px; }
    .stat { background:var(--card); border:1px solid var(--line); border-radius:14px; padding:18px; box-shadow:0 8px 24px rgba(0,0,0,.04); }
    .stat h3 { margin:0 0 10px; font-size:14px; color:var(--muted); font-weight:600; }
    .stat .num { font-size:34px; font-weight:700; }
    .section { background:var(--card); border:1px solid var(--line); border-radius:14px; box-shadow:0 8px 24px rgba(0,0,0,.04); margin-bottom:18px; overflow:hidden; }
    .section-head { padding:16px 18px; border-bottom:1px solid var(--line); font-size:18px; font-weight:700; }
    .section-body { padding:16px 18px; }
    .table-wrap { width:100%; overflow-x:auto; }
    table { width:100%; border-collapse:collapse; min-width:980px; }
    th, td { padding:12px 10px; border-bottom:1px solid var(--line); text-align:left; vertical-align:top; font-size:14px; }
    th { background:#f9fafb; font-size:13px; color:#374151; position:sticky; top:0; }
    .badge { display:inline-block; padding:5px 10px; border-radius:999px; font-size:12px; font-weight:700; white-space:nowrap; }
    .b-green { color:var(--green); background:var(--greenbg); }
    .b-amber { color:var(--amber); background:var(--amberbg); }
    .b-blue { color:var(--blue); background:var(--bluebg); }
    .b-red { color:var(--red); background:var(--redbg); }
    .muted { color:var(--muted); }
    .small { font-size:12px; color:var(--muted); }
    .mono { font-family: Consolas, Monaco, monospace; word-break:break-all; }
    @media (max-width: 980px) {
      .grid { grid-template-columns:repeat(2, minmax(0,1fr)); }
    }
    @media (max-width: 640px) {
      .grid { grid-template-columns:1fr; }
      .top-inner { flex-direction:column; align-items:flex-start; }
    }
  </style>
</head>
<body>
  <div class="top">
    <div class="top-inner">
      <div>
        <div class="title">Lalamove Shopify Admin</div>
        <div class="subtitle">Pending / matched / tracking-sent overview</div>
      </div>
      <form class="logout-form" method="post" action="">
        <button type="submit" name="logout" value="1">Logout</button>
      </form>
    </div>
  </div>

  <div class="container">
    <div class="grid">
      <div class="stat">
        <h3>Unmatched orders, last 24 hours</h3>
        <div class="num"><?php echo (int)$counts['unmatched_24h']; ?></div>
      </div>
      <div class="stat">
        <h3>Matched, waiting tracking send</h3>
        <div class="num"><?php echo (int)$counts['matched_waiting_tracking']; ?></div>
      </div>
      <div class="stat">
        <h3>Tracking sent, last 24 hours</h3>
        <div class="num"><?php echo (int)$counts['tracking_sent_24h']; ?></div>
      </div>
      <div class="stat">
        <h3>Office agents seen in last 15 mins</h3>
        <div class="num"><?php echo (int)$counts['office_online_15m']; ?></div>
      </div>
    </div>

    <div class="section">
      <div class="section-head">Office agent status</div>
      <div class="section-body table-wrap">
        <table>
          <thead>
            <tr>
              <th>Agent</th>
              <th>IP</th>
              <th>Last seen</th>
              <th>Last poll</th>
              <th>Status</th>
              <th>User agent</th>
            </tr>
          </thead>
          <tbody>
          <?php if (empty($officeAgents)): ?>
            <tr><td colspan="6" class="muted">No office agent data found.</td></tr>
          <?php else: ?>
            <?php foreach ($officeAgents as $row): ?>
              <tr>
                <td><?php echo h($row['agent_name']); ?></td>
                <td class="mono"><?php echo h($row['last_public_ip']); ?></td>
                <td><?php echo h($row['last_seen_at']); ?></td>
                <td><?php echo h($row['last_poll_at']); ?></td>
                <td>
                  <?php if ((int)$row['is_online'] === 1): ?>
                    <span class="badge b-green">Online</span>
                  <?php else: ?>
                    <span class="badge b-red">Offline</span>
                  <?php endif; ?>
                </td>
                <td class="small"><?php echo h($row['last_user_agent']); ?></td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>

    <div class="section">
      <div class="section-head">Recent order flow (last 3 days)</div>
      <div class="section-body table-wrap">
        <table>
          <thead>
            <tr>
              <th>Shopify</th>
              <th>Created</th>
              <th>Match status</th>
              <th>Decision</th>
              <th>Phone score</th>
              <th>Address score</th>
              <th>Lalamove order</th>
              <th>Tracking</th>
              <th>Share link</th>
              <th>Financial</th>
              <th>Fulfillment</th>
            </tr>
          </thead>
          <tbody>
          <?php if (empty($recentOrders)): ?>
            <tr><td colspan="11" class="muted">No recent orders found.</td></tr>
          <?php else: ?>
            <?php foreach ($recentOrders as $row): ?>
              <tr>
                <td>
                  <strong><?php echo h($row['shopify_name']); ?></strong><br>
                  <span class="small">Row ID: <?php echo (int)$row['id']; ?></span>
                </td>
                <td><?php echo h($row['order_created_at']); ?></td>
                <td>
                  <?php
                    $ms = (string)$row['match_status'];
                    $cls = 'b-amber';
                    if ($ms === 'tracking_sent') $cls = 'b-green';
                    elseif ($ms === 'matched') $cls = 'b-blue';
                    elseif ($ms === 'unmatched') $cls = 'b-amber';
                  ?>
                  <span class="badge <?php echo $cls; ?>"><?php echo h($ms); ?></span>
                </td>
                <td><?php echo h($row['match_decision'] ?? ''); ?></td>
                <td><?php echo h($row['phone_score'] ?? ''); ?></td>
                <td><?php echo h($row['address_score'] ?? ''); ?></td>
                <td class="mono"><?php echo h($row['lalamove_order_id'] ?? ''); ?></td>
                <td>
                  <?php if ((int)($row['tracking_sent'] ?? 0) === 1): ?>
                    <span class="badge b-green">Sent</span><br>
                    <span class="small"><?php echo h($row['tracking_sent_at'] ?? ''); ?></span>
                  <?php elseif (!empty($row['match_decision'])): ?>
                    <span class="badge b-blue">Waiting</span>
                  <?php else: ?>
                    <span class="badge b-amber">Pending</span>
                  <?php endif; ?>
                </td>
                <td class="mono small"><?php echo h($row['share_link'] ?? ''); ?></td>
                <td><?php echo h($row['financial_status'] ?? ''); ?></td>
                <td><?php echo h($row['fulfillment_status'] ?? ''); ?></td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</body>
</html>
