<?php
declare(strict_types=1);
require_once __DIR__ . '/_inc/boot.php';
require_once __DIR__ . '/_inc/db.php';

$pdo = db();
auth_require_any_permission(['manage_settings', 'manage_users']);
$title = 'Settings';
$active = 'settings';
$msg = '';
$authUser = auth_current_user();
$authRole = strtoupper((string)($authUser['role'] ?? ''));
$canManageUsers = auth_can('manage_users');
$canManageSettings = auth_can('manage_settings');

// Couriers table is the single source of truth.
// It supports country-specific templates via couriers.country_code.
// (GLOBAL is the fallback)
function upsert_courier(PDO $pdo, string $countryCode, string $code, string $name, string $prefix, int $strip): void {
  // If schema is old (no country_code), fallback to legacy behavior.
  $hasCountryCol = false;
  try {
    $st = $pdo->query("SHOW COLUMNS FROM couriers LIKE 'country_code'");
    $hasCountryCol = (bool)$st->fetch(PDO::FETCH_ASSOC);
  } catch (Throwable $e) {
    $hasCountryCol = false;
  }

  if ($hasCountryCol) {
    $st = $pdo->prepare("INSERT INTO couriers(country_code,code,name,track_prefix,strip_date_suffix,updated_at,active)
      VALUES(?,?,?,?,?,?,1)
      ON DUPLICATE KEY UPDATE
        name=VALUES(name),
        track_prefix=VALUES(track_prefix),
        strip_date_suffix=VALUES(strip_date_suffix),
        updated_at=VALUES(updated_at),
        active=1");
    $st->execute([$countryCode,$code,$name,$prefix,$strip,date('Y-m-d H:i:s')]);
  } else {
    $st = $pdo->prepare("INSERT INTO couriers(code,name,track_prefix,strip_date_suffix,updated_at)
      VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE name=VALUES(name), track_prefix=VALUES(track_prefix), strip_date_suffix=VALUES(strip_date_suffix), updated_at=VALUES(updated_at)");
    $st->execute([$code,$name,$prefix,$strip,date('Y-m-d H:i:s')]);
  }
}

function delete_courier(PDO $pdo, string $countryCode, string $code): void {
  $hasCountryCol = false;
  try {
    $st = $pdo->query("SHOW COLUMNS FROM couriers LIKE 'country_code'");
    $hasCountryCol = (bool)$st->fetch(PDO::FETCH_ASSOC);
  } catch (Throwable $e) {
    $hasCountryCol = false;
  }
  if ($hasCountryCol) {
    $st = $pdo->prepare("DELETE FROM couriers WHERE country_code=? AND code=?");
    $st->execute([$countryCode,$code]);
  } else {
    $st = $pdo->prepare("DELETE FROM couriers WHERE code=?");
    $st->execute([$code]);
  }
}


function kv_get(PDO $pdo, string $k, string $default=''): string {
  $st = $pdo->prepare("SELECT v FROM settings_kv WHERE k=?");
  $st->execute([$k]);
  $v = $st->fetchColumn();
  if ($v === false || $v === null) return $default;
  $v = (string)$v;
  return $v === '' ? $default : $v;
}
function kv_set(PDO $pdo, string $k, string $v): void {
  $st = $pdo->prepare("INSERT INTO settings_kv(k,v,updated_at) VALUES(?,?,?) ON DUPLICATE KEY UPDATE v=VALUES(v), updated_at=VALUES(updated_at)");
  $st->execute([$k,$v,date('Y-m-d H:i:s')]);
}
function parse_country_list(string $s): array {
  $parts = preg_split('/[,\s]+/', strtoupper($s));
  $out = [];
  foreach ($parts as $p) {
    $p = trim((string)$p);
    if ($p==='') continue;
    $p = preg_replace('/[^A-Z0-9_\-]/','',$p);
    if ($p==='') continue;
    $out[] = $p;
  }
  $out = array_values(array_unique($out));
  return $out;
}

function upsert_card(PDO $pdo, string $country, string $sku, string $name, int $active): void {
  $st = $pdo->prepare("INSERT INTO cards(country,sku,name,active,manual_stock_qty,last_stock_qty,last_stock_at,default_per_awb)
    VALUES(?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE name=VALUES(name), active=VALUES(active)");
  $now = date('Y-m-d H:i:s');
  $st->execute([$country,$sku,$name,$active,0,0,$now,0]);
}

function permission_label(string $key): string {
  $map = [
    'view_dashboard' => 'View dashboard/pages',
    'use_send' => 'Use SEND',
    'use_crons' => 'Use CRONS',
    'manage_settings' => 'Manage system settings',
    'manage_users' => 'Manage users',
  ];
  return $map[$key] ?? $key;
}

function permission_kind(string $key): string {
  if (in_array($key, ['use_send', 'use_crons'], true)) return 'sensitive';
  if (in_array($key, ['manage_settings', 'manage_users'], true)) return 'admin';
  return 'default';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $op = (string)($_POST['op'] ?? '');

  try {
    if ($op === 'create_user') {
      if (!$canManageUsers) throw new RuntimeException('Forbidden.');
      $username = trim((string)($_POST['username'] ?? ''));
      $fullName = trim((string)($_POST['full_name'] ?? ''));
      $role = strtoupper(trim((string)($_POST['role'] ?? 'AGENT')));
      $password = (string)($_POST['password'] ?? '');
      $activeFlag = isset($_POST['active']) ? 1 : 0;

      if ($username === '' || $fullName === '' || $password === '') throw new RuntimeException('Username, full name and password are required.');
      if (!auth_can_manage_role($authRole, $role)) throw new RuntimeException('You cannot create that role.');
      if (strlen($password) < 8) throw new RuntimeException('Password must have at least 8 characters.');

      $now = date('Y-m-d H:i:s');
      $st = $pdo->prepare("INSERT INTO users(username, full_name, password_hash, role, active, must_change_password, created_at, updated_at)
        VALUES(?,?,?,?,?,?,?,?)");
      $st->execute([$username, $fullName, password_hash($password, PASSWORD_DEFAULT), $role, $activeFlag, 1, $now, $now]);
      $msg = "User created.";
    }

    if ($op === 'update_user') {
      if (!$canManageUsers) throw new RuntimeException('Forbidden.');
      $id = (int)($_POST['id'] ?? 0);
      $username = trim((string)($_POST['username'] ?? ''));
      $fullName = trim((string)($_POST['full_name'] ?? ''));
      $role = strtoupper(trim((string)($_POST['role'] ?? 'AGENT')));
      $password = (string)($_POST['password'] ?? '');
      $activeFlag = isset($_POST['active']) ? 1 : 0;
      $forcePassword = isset($_POST['must_change_password']) ? 1 : 0;
      if ($id <= 0 || $username === '' || $fullName === '') throw new RuntimeException('Missing user data.');

      $stUser = $pdo->prepare("SELECT id, role FROM users WHERE id=? LIMIT 1");
      $stUser->execute([$id]);
      $targetUser = $stUser->fetch(PDO::FETCH_ASSOC);
      if (!$targetUser) throw new RuntimeException('User not found.');
      if (!auth_can_manage_role($authRole, $role) || !auth_can_manage_user($authUser ?? [], $targetUser)) {
        throw new RuntimeException('You cannot edit that user.');
      }
      if (strtoupper((string)$targetUser['role']) === 'OWNER' && ($role !== 'OWNER' || $activeFlag !== 1)) {
        $owners = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE role='OWNER' AND active=1")->fetchColumn();
        if ($owners <= 1) throw new RuntimeException('At least one active OWNER must remain.');
      }

      $sets = ['username=?', 'full_name=?', 'role=?', 'active=?', 'must_change_password=?', 'updated_at=?'];
      $args = [$username, $fullName, $role, $activeFlag, $forcePassword, date('Y-m-d H:i:s')];
      if ($password !== '') {
        if (strlen($password) < 8) throw new RuntimeException('Password must have at least 8 characters.');
        $sets[] = 'password_hash=?';
        $args[] = password_hash($password, PASSWORD_DEFAULT);
      }
      $args[] = $id;
      $sql = "UPDATE users SET " . implode(',', $sets) . " WHERE id=?";
      $pdo->prepare($sql)->execute($args);
      $msg = "User updated.";
    }

    if ($op === 'delete_user') {
      if (!$canManageUsers) throw new RuntimeException('Forbidden.');
      $id = (int)($_POST['id'] ?? 0);
      if ($id <= 0) throw new RuntimeException('Missing user id.');

      $stUser = $pdo->prepare("SELECT id, role FROM users WHERE id=? LIMIT 1");
      $stUser->execute([$id]);
      $targetUser = $stUser->fetch(PDO::FETCH_ASSOC);
      if (!$targetUser) throw new RuntimeException('User not found.');
      if (!auth_can_manage_user($authUser ?? [], $targetUser)) throw new RuntimeException('You cannot delete that user.');
      if (strtoupper((string)$targetUser['role']) === 'OWNER') {
        $owners = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE role='OWNER' AND active=1")->fetchColumn();
        if ($owners <= 1) throw new RuntimeException('At least one active OWNER must remain.');
      }

      $pdo->prepare("DELETE FROM users WHERE id=?")->execute([$id]);
      $msg = "User deleted.";
    }

    if (!$canManageSettings && $op !== '') {
      throw new RuntimeException('Only OWNER can change system settings.');
    }

    if ($op === 'save_role_permissions') {
      $role = strtoupper(trim((string)($_POST['role'] ?? '')));
      if ($authRole !== 'OWNER') throw new RuntimeException('Only OWNER can change role permissions.');
      if (!in_array($role, auth_roles(), true)) throw new RuntimeException('Invalid role.');
      $selected = [];
      foreach (auth_permission_keys() as $permissionKey) {
        $selected[$permissionKey] = isset($_POST['perm'][$permissionKey]) ? 1 : 0;
      }
      auth_save_role_permissions($role, $selected);
      $msg = "Permissions updated for {$role}.";
    }

    if ($op === 'save_courier') {
      $code = strtoupper(trim((string)$_POST['code']));
      $name = trim((string)$_POST['name']);
      $prefix = trim((string)$_POST['prefix']);
      $strip = isset($_POST['strip']) ? 1 : 0;
      $cc = strtoupper(trim((string)($_POST['country_code'] ?? 'GLOBAL')));
      if ($code === '' || $name === '') throw new RuntimeException("Courier code and name are required.");

      upsert_courier($pdo, $cc, $code, $name, $prefix, $strip);
      $msg = "Courier saved for {$cc}.";

      // PRG: reload the same country tab so the newly saved row is visible immediately
      $redir = 'settings.php';
      $redir .= '?ct_country=' . urlencode($cc);
      header('Location: ' . $redir);
      exit;
    }

    if ($op === 'delete_courier') {
      $code = strtoupper(trim((string)$_POST['code']));
      if ($code === 'DEFAULT') throw new RuntimeException("Cannot delete DEFAULT courier.");
      $cc = strtoupper(trim((string)($_POST['country_code'] ?? 'GLOBAL')));
      delete_courier($pdo, $cc, $code);
      $msg = "Courier deleted.";
    }

    if ($op === 'save_card') {
      $country = strtoupper(trim((string)$_POST['country']));
      $sku = trim((string)$_POST['sku']);
      $name = trim((string)$_POST['name']);
      $active = isset($_POST['active']) ? 1 : 0;
      $stock = max(0, (int)($_POST['manual_stock_qty'] ?? 0));
      $defaultPerAwb = max(0, (int)($_POST['default_per_awb'] ?? 0));
      if ($country==='' || $sku==='' || $name==='') throw new RuntimeException("Country, SKU and name are required.");
      $now = date('Y-m-d H:i:s');
      $st = $pdo->prepare("INSERT INTO cards(country,sku,name,active,manual_stock_qty,last_stock_qty,last_stock_at,default_per_awb)
        VALUES(?,?,?,?,?,?,?,?)
        ON DUPLICATE KEY UPDATE name=VALUES(name), active=VALUES(active), manual_stock_qty=VALUES(manual_stock_qty), default_per_awb=VALUES(default_per_awb)");
      $st->execute([$country,$sku,$name,$active,$stock,$stock,$now,$defaultPerAwb]);
      $msg = "Card saved.";
    }

    if ($op === 'update_card') {
      $id = (int)($_POST['id'] ?? 0);
      $country = strtoupper(trim((string)$_POST['country']));
      $sku = trim((string)$_POST['sku']);
      $name = trim((string)$_POST['name']);
      $active = isset($_POST['active']) ? 1 : 0;
      $stock = max(0, (int)($_POST['manual_stock_qty'] ?? 0));
      $defaultPerAwb = max(0, (int)($_POST['default_per_awb'] ?? 0));
      if ($id<=0 || $country==='' || $sku==='' || $name==='') throw new RuntimeException("Card id, country, SKU and name are required.");
      $st = $pdo->prepare("UPDATE cards SET country=?, sku=?, name=?, active=?, manual_stock_qty=?, last_stock_qty=?, last_stock_at=?, default_per_awb=? WHERE id=?");
      $st->execute([$country,$sku,$name,$active,$stock,$stock,date('Y-m-d H:i:s'),$defaultPerAwb,$id]);
      $msg = "Card updated.";
    }

    if ($op === 'delete_card') {
      $id = (int)($_POST['id'] ?? 0);
      if ($id<=0) throw new RuntimeException("Missing card id");
      $st = $pdo->prepare("DELETE FROM cards WHERE id=?");
      $st->execute([$id]);
      $msg = "Card deleted.";
    }


    if ($op === 'save_backfill') {
      $list = trim((string)$_POST['backfill_countries']);
      $codes = parse_country_list($list);
      kv_set($pdo, 'backfill_countries', implode(',', $codes));

      // ensure countries exist and are enabled
      foreach ($codes as $cc) {
        $st = $pdo->prepare("INSERT INTO countries(code,name,api_value,enabled,show_on_home,updated_at)
          VALUES(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE enabled=VALUES(enabled), show_on_home=VALUES(show_on_home), updated_at=VALUES(updated_at)");
        $st->execute([$cc, ucfirst(strtolower($cc)), $cc, 1, 1, date('Y-m-d H:i:s')]);
      }
      $msg = "Backfill countries saved.";
    }

    if ($op === 'save_pickpack_settings') {
      $baseUrl = trim((string)($_POST['base_url'] ?? 'https://my.pickpack.hr/API/1.0'));
      $userId = trim((string)($_POST['user_id'] ?? ''));
      $apiKey = trim((string)($_POST['api_key'] ?? ''));
      $channelId = trim((string)($_POST['channel_id'] ?? ''));
      $codAmount = trim((string)($_POST['cod_amount'] ?? '40'));
      $currency = strtoupper(trim((string)($_POST['currency'] ?? 'EUR')));

      if ($baseUrl === '') $baseUrl = 'https://my.pickpack.hr/API/1.0';
      if ($userId === '') throw new RuntimeException('Pick&Pack userID is required.');
      if ($channelId === '') throw new RuntimeException('Pick&Pack channelID is required.');
      if ($codAmount === '' || !is_numeric($codAmount)) throw new RuntimeException('Pick&Pack COD amount must be numeric.');
      if ($currency === '') $currency = 'EUR';

      kv_set($pdo, 'pickpack_base_url', $baseUrl);
      kv_set($pdo, 'pickpack_user_id', $userId);
      if ($apiKey !== '') kv_set($pdo, 'pickpack_api_key', $apiKey);
      kv_set($pdo, 'pickpack_channel_id', $channelId);
      kv_set($pdo, 'pickpack_cod_amount', (string)$codAmount);
      kv_set($pdo, 'pickpack_currency', $currency);
      $msg = 'Pick&Pack settings saved.';
    }

    if ($op === 'add_country') {
      $code = strtoupper(trim((string)($_POST['code'] ?? '')));
      $name = trim((string)($_POST['name'] ?? ''));
      $apiValue = trim((string)($_POST['api_value'] ?? ''));
      $provider = strtoupper(trim((string)($_POST['fulfillment_provider'] ?? 'EFC')));
      if ($code === '') throw new RuntimeException('Country code is required.');
      $code = preg_replace('/[^A-Z0-9_\-]/', '', $code);
      if ($code === '') throw new RuntimeException('Invalid country code.');
      if ($name === '') $name = ucfirst(strtolower(str_replace(['_', '-'], ' ', $code)));
      if ($apiValue === '') $apiValue = $code;
      if (!in_array($provider, ['EFC','QCARGO','PICKPACK'], true)) $provider = 'EFC';
      $st = $pdo->prepare("INSERT INTO countries(code,name,api_value,enabled,show_on_home,fulfillment_provider,default_courier_code,updated_at)
        VALUES(?,?,?,?,?,?,?,?)
        ON DUPLICATE KEY UPDATE name=VALUES(name), api_value=VALUES(api_value), enabled=VALUES(enabled), show_on_home=VALUES(show_on_home), fulfillment_provider=VALUES(fulfillment_provider), updated_at=VALUES(updated_at)");
      $st->execute([$code, $name, $apiValue, 1, 1, $provider, null, date('Y-m-d H:i:s')]);
      $msg = "Country {$code} saved.";
    }

    if ($op === 'update_country') {
      $code = strtoupper(trim((string)$_POST['code']));
      if ($code==='') throw new RuntimeException("Missing country code");
      $en = (int)($_POST['enabled'] ?? 0) ? 1 : 0;
      $show = (int)($_POST['show_on_home'] ?? 0) ? 1 : 0;
      $apiv = trim((string)($_POST['api_value'] ?? ''));
      $provider = strtoupper(trim((string)($_POST['fulfillment_provider'] ?? 'EFC')));
      if (!in_array($provider, ['EFC','QCARGO','PICKPACK'], true)) $provider = 'EFC';
      $defaultCourier = strtoupper(trim((string)($_POST['default_courier_code'] ?? '')));
      $st = $pdo->prepare("UPDATE countries SET enabled=?, show_on_home=?, api_value=?, fulfillment_provider=?, default_courier_code=?, updated_at=? WHERE code=?");
      $st->execute([$en, $show, ($apiv===''?null:$apiv), $provider, ($defaultCourier===''?null:$defaultCourier), date('Y-m-d H:i:s'), $code]);
      $msg = "Country updated.";
    }

    if ($op === 'sync_countries_api') {
      require_once __DIR__ . '/_inc/token.php';
      require_once __DIR__ . '/_inc/efc.php';
      $cfg = app_cfg();
      $client = new EfcClient($cfg);
      $token = efc_token();
      $res = $client->getCountries($token);

      $list = $res['data'] ?? $res['countries'] ?? $res;
      if (!is_array($list)) $list = [];

      $inserted = 0;
      foreach ($list as $row) {
        $name = '';
        $code = '';
        $apiValue = '';

        if (is_string($row)) {
          $name = $row;
          $apiValue = $row;
          $code = strtoupper(preg_replace('/[^A-Z0-9_\-]/','', $row));
        } elseif (is_array($row)) {
          $name = (string)($row['name'] ?? $row['country'] ?? $row['label'] ?? '');
          $code = (string)($row['code'] ?? $row['country_code'] ?? $row['id'] ?? '');
          $apiValue = (string)($row['api_value'] ?? $row['apiValue'] ?? $row['value'] ?? $name ?? $code);
          if ($code==='') $code = strtoupper(preg_replace('/[^A-Z0-9_\-]/','', $name));
        }
        $code = strtoupper(trim($code));
        if ($code==='') continue;
        if ($name==='') $name = ucfirst(strtolower($code));
        if ($apiValue==='') $apiValue = $code;

        $st = $pdo->prepare("INSERT INTO countries(code,name,api_value,enabled,show_on_home,updated_at)
          VALUES(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE name=VALUES(name), api_value=VALUES(api_value), updated_at=VALUES(updated_at)");
        $st->execute([$code,$name,$apiValue,0,1,date('Y-m-d H:i:s')]);
        $inserted++;
      }
      $msg = "Synced countries from API: {$inserted}. (Enabled flags kept unless new.)";
    }

  } catch (Throwable $e) {
    $msg = "ERROR: " . $e->getMessage();
  }
}

// --- Country-specific couriers (single table)
$pdo->prepare("INSERT INTO countries(code,name,api_value,enabled,show_on_home,fulfillment_provider,default_courier_code,updated_at)
  VALUES(?,?,?,?,?,?,?,?)
  ON DUPLICATE KEY UPDATE name=VALUES(name), api_value=VALUES(api_value), enabled=VALUES(enabled), show_on_home=VALUES(show_on_home), fulfillment_provider=VALUES(fulfillment_provider), default_courier_code=VALUES(default_courier_code), updated_at=VALUES(updated_at)")
  ->execute(['ROMANIA','Romania','ROMANIA',1,1,'QCARGO','SAMEDAY',date('Y-m-d H:i:s')]);
upsert_courier($pdo, 'ROMANIA', 'SAMEDAY', 'Sameday Romania', 'https://sameday.ro/status-colet/?awb=', 0);

$countries_enabled = $pdo->query("SELECT code,name,api_value,COALESCE(fulfillment_provider,'EFC') fulfillment_provider FROM countries WHERE enabled=1 ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
$ctCountry = strtoupper(trim((string)($_GET['ct_country'] ?? 'GLOBAL')));
if ($ctCountry === '') $ctCountry = 'GLOBAL';

// detect schema
$hasCountryCol = false;
try {
  $st = $pdo->query("SHOW COLUMNS FROM couriers LIKE 'country_code'");
  $hasCountryCol = (bool)$st->fetch(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
  $hasCountryCol = false;
}

if ($hasCountryCol) {
  $st = $pdo->prepare("SELECT country_code, code, name, track_prefix, strip_date_suffix, updated_at, active FROM couriers WHERE country_code=? ORDER BY code");
  $st->execute([$ctCountry]);
  $couriers = $st->fetchAll(PDO::FETCH_ASSOC);
} else {
  $couriers = $pdo->query("SELECT code, name, track_prefix, strip_date_suffix, updated_at, 1 AS active FROM couriers ORDER BY code")->fetchAll(PDO::FETCH_ASSOC);
}

$countries = $pdo->query("SELECT code,name FROM countries WHERE enabled=1 ORDER BY name")->fetchAll();
$countriesAll = $pdo->query("SELECT code,name,COALESCE(NULLIF(api_value,''), code) api_value, enabled, COALESCE(show_on_home,1) show_on_home, COALESCE(fulfillment_provider,'EFC') fulfillment_provider, COALESCE(default_courier_code,'') default_courier_code FROM countries ORDER BY name")->fetchAll();
$backfillCountries = kv_get($pdo, 'backfill_countries', 'SPAIN');
$pickpackSettings = [
  'base_url' => kv_get($pdo, 'pickpack_base_url', 'https://my.pickpack.hr/API/1.0'),
  'user_id' => kv_get($pdo, 'pickpack_user_id', ''),
  'api_key_set' => kv_get($pdo, 'pickpack_api_key', '') !== '',
  'channel_id' => kv_get($pdo, 'pickpack_channel_id', ''),
  'cod_amount' => kv_get($pdo, 'pickpack_cod_amount', '40'),
  'currency' => kv_get($pdo, 'pickpack_currency', 'EUR'),
];
$cards = $pdo->query("SELECT * FROM cards ORDER BY country, name")->fetchAll();
$users = [];
if ($canManageUsers) {
  if ($authRole === 'ADMIN') {
    $stUsers = $pdo->prepare("SELECT id, username, full_name, role, active, must_change_password, last_login_at, created_at
      FROM users
      WHERE id=? OR role='AGENT'
      ORDER BY CASE WHEN id=? THEN 0 ELSE 1 END, full_name, username");
    $stUsers->execute([(int)($authUser['id'] ?? 0), (int)($authUser['id'] ?? 0)]);
    $users = $stUsers->fetchAll(PDO::FETCH_ASSOC);
  } else {
    $users = $pdo->query("SELECT id, username, full_name, role, active, must_change_password, last_login_at, created_at FROM users ORDER BY role, full_name, username")->fetchAll(PDO::FETCH_ASSOC);
  }
}
$manageableRoles = auth_manageable_roles_for($authRole);
$rolePermissionMap = auth_permission_map();
$userStats = [
  'total' => count($users),
  'active' => 0,
  'must_change' => 0,
  'by_role' => array_fill_keys(auth_roles(), 0),
];
foreach ($users as $u) {
  if ((int)($u['active'] ?? 0) === 1) $userStats['active']++;
  if ((int)($u['must_change_password'] ?? 0) === 1) $userStats['must_change']++;
  $roleKey = strtoupper((string)($u['role'] ?? ''));
  if (isset($userStats['by_role'][$roleKey])) $userStats['by_role'][$roleKey]++;
}

require_once __DIR__ . '/_inc/layout_top.php';
?>

<?php if ($canManageUsers): ?>
<section class="card user-admin-card">
  <div class="card-h">
    <div class="card-title">Users & Roles</div>
    <div class="muted"><?= $canManageSettings ? 'OWNER can manage all users and roles.' : 'ADMIN can manage only AGENT users and can also see their own account.' ?></div>
  </div>

  <?php if($msg): ?>
    <div class="pill" style="margin-bottom:12px"><?= h($msg) ?></div>
  <?php endif; ?>

  <div class="user-summary-grid">
    <div class="mini-stat"><div class="k">Total</div><div class="v"><?= (int)$userStats['total'] ?></div></div>
    <div class="mini-stat"><div class="k">Active</div><div class="v"><?= (int)$userStats['active'] ?></div></div>
    <div class="mini-stat"><div class="k">Force password</div><div class="v"><?= (int)$userStats['must_change'] ?></div></div>
    <?php foreach(auth_roles() as $role): ?>
      <div class="mini-stat"><div class="k"><?= h($role) ?></div><div class="v"><?= (int)($userStats['by_role'][$role] ?? 0) ?></div></div>
    <?php endforeach; ?>
  </div>

  <div class="user-card-grid">
    <?php foreach($users as $u): ?>
      <?php $canEditUser = auth_can_manage_user($authUser ?? [], $u); ?>
      <form method="post" class="user-card">
        <input type="hidden" name="op" value="update_user" />
        <input type="hidden" name="id" value="<?= (int)$u['id'] ?>" />

        <div class="user-card-top">
          <div>
            <div class="user-card-name"><?= h($u['full_name']) ?></div>
            <div class="user-card-username">@<?= h($u['username']) ?></div>
          </div>
          <div class="user-card-badges">
            <span class="badge"><?= h($u['role']) ?></span>
            <span class="badge <?= ((int)$u['active']===1)?'badge-good':'badge-warn' ?>"><?= ((int)$u['active']===1)?'ACTIVE':'OFF' ?></span>
            <?php if ((int)$u['must_change_password']===1): ?>
              <span class="badge badge-warn">RESET PW</span>
            <?php endif; ?>
          </div>
        </div>

        <div class="user-card-grid-inner">
          <div class="field">
            <label class="lbl">Username</label>
            <input class="inp" name="username" value="<?= h($u['username']) ?>" <?= $canEditUser ? '' : 'disabled' ?> />
          </div>
          <div class="field">
            <label class="lbl">Full name</label>
            <input class="inp" name="full_name" value="<?= h($u['full_name']) ?>" <?= $canEditUser ? '' : 'disabled' ?> />
          </div>
          <div class="field">
            <label class="lbl">Role</label>
            <?php if ($canEditUser && (int)$u['id'] !== (int)($authUser['id'] ?? 0)): ?>
              <select class="inp" name="role">
                <?php foreach($manageableRoles as $role): ?>
                  <option value="<?= h($role) ?>" <?= strtoupper((string)$u['role']) === $role ? 'selected' : '' ?>><?= h($role) ?></option>
                <?php endforeach; ?>
                <?php if (!in_array(strtoupper((string)$u['role']), $manageableRoles, true)): ?>
                  <option value="<?= h($u['role']) ?>" selected><?= h($u['role']) ?></option>
                <?php endif; ?>
              </select>
            <?php else: ?>
              <div class="inp user-static-field"><?= h($u['role']) ?></div>
            <?php endif; ?>
          </div>
          <div class="field">
            <label class="lbl">New password</label>
            <?php if ($canEditUser): ?>
              <input class="inp" type="password" name="password" placeholder="Leave empty to keep current" />
            <?php else: ?>
              <div class="inp user-static-field">Hidden</div>
            <?php endif; ?>
          </div>
        </div>

        <div class="user-meta-row">
          <div class="user-meta-box">
            <div class="k">Last login</div>
            <div class="v"><?= h(dd($u['last_login_at'])) ?: 'Never' ?></div>
          </div>
          <div class="user-meta-box">
            <div class="k">Created</div>
            <div class="v"><?= h(dd($u['created_at'])) ?></div>
          </div>
        </div>

        <div class="user-toggle-row">
          <label class="perm-row">
            <input type="checkbox" name="active" value="1" <?= ((int)$u['active']===1)?'checked':'' ?> <?= $canEditUser ? '' : 'disabled' ?> />
            <span>Active account</span>
          </label>
          <label class="perm-row">
            <input type="checkbox" name="must_change_password" value="1" <?= ((int)$u['must_change_password']===1)?'checked':'' ?> <?= $canEditUser ? '' : 'disabled' ?> />
            <span>Force password change</span>
          </label>
        </div>

        <div class="user-card-actions">
          <?php if ($canEditUser): ?>
            <button class="btn btn-sm btn-ghost" type="submit">Save user</button>
          <?php endif; ?>
          <?php if ($canEditUser && (int)$u['id'] !== (int)($authUser['id'] ?? 0)): ?>
            <button class="btn btn-sm btn-ghost" formaction="/settings.php" formmethod="post" name="op" value="delete_user" onclick="return confirm('Delete user?')">Delete</button>
            <input type="hidden" name="id" value="<?= (int)$u['id'] ?>" />
          <?php endif; ?>
        </div>
      </form>
    <?php endforeach; ?>
  </div>

  <?php if ($manageableRoles): ?>
    <div class="sep"></div>
    <form class="user-create-card" method="post">
      <input type="hidden" name="op" value="create_user" />
      <div class="user-create-head">
        <div class="card-title">Create User</div>
        <div class="muted small">New users will be forced to change password on first login.</div>
      </div>
      <div class="user-card-grid-inner">
        <div class="field">
          <label class="lbl">Username</label>
          <input class="inp" name="username" placeholder="Username" />
        </div>
        <div class="field">
          <label class="lbl">Full name</label>
          <input class="inp" name="full_name" placeholder="Full name" />
        </div>
        <div class="field">
          <label class="lbl">Role</label>
          <select class="inp" name="role">
            <?php foreach($manageableRoles as $role): ?>
              <option value="<?= h($role) ?>"><?= h($role) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="field">
          <label class="lbl">Temporary password</label>
          <input class="inp" type="password" name="password" placeholder="Temporary password" />
        </div>
      </div>
      <div class="user-card-actions">
        <label class="perm-row">
          <input type="checkbox" name="active" checked />
          <span>Active account</span>
        </label>
        <button class="btn" type="submit">Create user</button>
      </div>
    </form>
  <?php endif; ?>
</section>
<?php endif; ?>

<?php if ($canManageSettings): ?>
<section class="card" style="margin-top:16px">
  <div class="card-h">
    <div class="card-title">Role Permissions</div>
    <div class="muted">OWNER can choose what each role can see and use.</div>
  </div>

  <div class="role-grid">
    <?php foreach(auth_roles() as $role): ?>
      <form method="post" class="role-card">
        <input type="hidden" name="op" value="save_role_permissions" />
        <input type="hidden" name="role" value="<?= h($role) ?>" />
        <div class="role-head">
          <div class="badge"><?= h($role) ?></div>
        </div>
        <div class="role-perms">
          <?php foreach(auth_permission_keys() as $permissionKey): ?>
            <label class="perm-row perm-row-<?= h(permission_kind($permissionKey)) ?>">
              <input type="checkbox" name="perm[<?= h($permissionKey) ?>]" value="1" <?= !empty($rolePermissionMap[$role][$permissionKey]) ? 'checked' : '' ?> <?= $role === 'OWNER' ? 'disabled' : '' ?> />
              <span><?= h(permission_label($permissionKey)) ?></span>
            </label>
          <?php endforeach; ?>
        </div>
        <?php if ($role === 'OWNER'): ?>
          <div class="muted small">OWNER stays full-access.</div>
        <?php else: ?>
          <button class="btn btn-sm btn-ghost" type="submit">Save permissions</button>
        <?php endif; ?>
      </form>
    <?php endforeach; ?>
  </div>
</section>

<section class="card">
  <div class="card-h">
    <div class="card-title">Tracking templates (Couriers)</div>
    <div class="muted">prefix + tracking (optional strip YYYYMMDD suffix)</div>
  </div>

  <?php if($msg): ?>
    <div class="pill" style="margin-bottom:12px"><?= h($msg) ?></div>
  <?php endif; ?>


  <form method="get" class="row" style="gap:10px; align-items:flex-end; margin: 10px 0 14px 0;">
    <div style="min-width:260px">
      <div class="muted" style="font-size:12px; margin-bottom:6px;">Country</div>
      <select class="input" name="ct_country" onchange="this.form.submit()">
        <option value="GLOBAL" <?= ($ctCountry==='GLOBAL')?'selected':'' ?>>GLOBAL (fallback)</option>
        <?php foreach($countries_enabled as $cc): ?>
          <option value="<?= h($cc['code']) ?>" <?= ($ctCountry===$cc['code'])?'selected':'' ?>>
            <?= h($cc['name']) ?> (<?= h($cc['code']) ?>)
          </option>
        <?php endforeach; ?>
      </select>
    </div>
    <noscript><button class="btn btn-sm" type="submit">Load</button></noscript>
  </form>

  <div class="muted" style="margin-bottom:10px;">
    Showing templates for: <strong><?= h($ctCountry) ?></strong>
  </div>
  <div class="table-wrap">
    <table class="table">
      <thead>
        <tr>
          <th>Code</th><th>Name</th><th>Track prefix</th><th>Strip date suffix</th><th>Active</th><th></th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($couriers as $c): ?>
          <tr>
            <td><strong><?= h($c['code']) ?></strong></td>
            <td><?= h($c['name']) ?></td>
            <td class="muted"><?= h($c['track_prefix']) ?></td>
            <td><?= ((int)$c['strip_date_suffix']===1)?'YES':'NO' ?></td>
            <?php if(isset($c['active'])): ?>
              <td><?= ((int)$c['active']===1)?'YES':'NO' ?></td>
            <?php else: ?>
              <td>YES</td>
            <?php endif; ?>
            <td class="right">
              <?php if($c['code']!=='DEFAULT'): ?>
              <form method="post" style="display:inline">
                <input type="hidden" name="op" value="delete_courier" />
                <input type="hidden" name="code" value="<?= h($c['code']) ?>" />
                <input type="hidden" name="country_code" value="<?= h($ctCountry) ?>" />
                <button class="btn btn-sm btn-ghost" type="submit" onclick="return confirm('Delete courier?')">Delete</button>
              </form>
              <?php endif; ?>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <div class="sep"></div>

  <form class="row" method="post">
    <input type="hidden" name="op" value="save_courier" />
        <input type="hidden" name="country_code" value="<?= h($ctCountry) ?>" />
    <input class="input" name="code" placeholder="CODE (e.g. GLS)" style="max-width:140px" />
    <input class="input" name="name" placeholder="Name" style="max-width:220px" />
    <input class="input" name="prefix" placeholder="Track prefix (e.g. https://gls-group.eu/track?match=)" />
    <label class="toggle" style="gap:8px">
      <input type="checkbox" name="strip" checked />
      <span class="toggle-ui" aria-hidden="true"></span>
      <span>Strip YYYYMMDD</span>
    </label>
    <button class="btn" type="submit">Save courier</button>
  </form>
</section>

<section class="card" style="margin-top:16px">
  <div class="card-h">
    <div class="card-title">Pick&Pack</div>
    <div class="muted">Credentials used for countries where provider is Pick&Pack.</div>
  </div>

  <form class="row" method="post" style="align-items:end; flex-wrap:wrap">
    <input type="hidden" name="op" value="save_pickpack_settings" />
    <div style="min-width:260px">
      <div class="muted small" style="margin-bottom:6px">Base URL</div>
      <input class="input" name="base_url" value="<?= h($pickpackSettings['base_url']) ?>" />
    </div>
    <div style="min-width:120px">
      <div class="muted small" style="margin-bottom:6px">userID</div>
      <input class="input" name="user_id" value="<?= h($pickpackSettings['user_id']) ?>" />
    </div>
    <div style="min-width:260px">
      <div class="muted small" style="margin-bottom:6px">pickPackApiKey <?= $pickpackSettings['api_key_set'] ? '(saved)' : '' ?></div>
      <input class="input" name="api_key" value="" placeholder="<?= $pickpackSettings['api_key_set'] ? 'Leave blank to keep current key' : 'Required' ?>" />
    </div>
    <div style="min-width:120px">
      <div class="muted small" style="margin-bottom:6px">channelID</div>
      <input class="input" name="channel_id" value="<?= h($pickpackSettings['channel_id']) ?>" />
    </div>
    <div style="min-width:120px">
      <div class="muted small" style="margin-bottom:6px">COD amount</div>
      <input class="input" name="cod_amount" value="<?= h($pickpackSettings['cod_amount']) ?>" />
    </div>
    <div style="min-width:100px">
      <div class="muted small" style="margin-bottom:6px">Currency</div>
      <input class="input" name="currency" value="<?= h($pickpackSettings['currency']) ?>" />
    </div>
    <button class="btn" type="submit">Save Pick&Pack</button>
  </form>
</section>


<section class="card" style="margin-top:16px">
  <div class="card-h">
    <div class="card-title">Countries (enabled) + Backfill selection</div>
    <div class="muted">Backfill runs only for countries you enter below. Enable also controls Home + regular sync.</div>
  </div>

  <?php if($msg): ?>
    <div class="pill" style="margin-bottom:12px"><?= h($msg) ?></div>
  <?php endif; ?>

  <form class="row" method="post" style="align-items:end; flex-wrap:wrap">
    <input type="hidden" name="op" value="save_backfill" />
    <div style="flex:1; min-width:280px">
      <div class="muted small" style="margin-bottom:6px">Backfill countries (comma/space separated codes, e.g. SPAIN, ITALY, ROMANIA)</div>
      <input class="input" name="backfill_countries" value="<?= h($backfillCountries) ?>" />
    </div>
    <button class="btn" type="submit">Save</button>
    <a class="btn btn-ghost" href="/crons.php">Run backfill</a>
  </form>

  <div class="sep"></div>

  <form method="post" style="margin-bottom:12px">
    <input type="hidden" name="op" value="sync_countries_api" />
    <button class="btn btn-ghost" type="submit">Sync countries from EFC API</button>
    <span class="muted small" style="margin-left:10px">This fills/updates the Countries table with API values (api_value).</span>
  </form>

  <form class="row" method="post" style="align-items:end; flex-wrap:wrap; margin-bottom:12px">
    <input type="hidden" name="op" value="add_country" />
    <div style="min-width:150px">
      <div class="muted small" style="margin-bottom:6px">Code</div>
      <input class="input" name="code" placeholder="CROATIA" />
    </div>
    <div style="min-width:200px">
      <div class="muted small" style="margin-bottom:6px">Name</div>
      <input class="input" name="name" placeholder="Croatia" />
    </div>
    <div style="min-width:180px">
      <div class="muted small" style="margin-bottom:6px">API value</div>
      <input class="input" name="api_value" placeholder="hr / CROATIA / ..." />
    </div>
    <div style="min-width:150px">
      <div class="muted small" style="margin-bottom:6px">Provider</div>
      <select class="input" name="fulfillment_provider">
        <option value="EFC">EFC</option>
        <option value="QCARGO">QCargo</option>
        <option value="PICKPACK">Pick&Pack</option>
      </select>
    </div>
    <button class="btn" type="submit">Add country</button>
  </form>

  <div class="table-wrap">
    <table class="table">
      <thead>
        <tr>
          <th>Code</th>
          <th>Name</th>
          <th>API value (sent to /api/leads?country=...)</th>
          <th>Provider</th>
          <th>Default courier</th>
          <th>Enabled</th>
          <th>Show on Home</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($countriesAll as $c): ?>
          <?php $countryFormId = 'f_' . preg_replace('/[^A-Za-z0-9_-]/', '_', (string)$c['code']); ?>
          <tr data-country-row="<?= h($c['code']) ?>">
            <td><strong><?= h($c['code']) ?></strong></td>
            <td><?= h($c['name']) ?></td>
            <td class="muted">
              <input class="input" name="api_value" form="<?= h($countryFormId) ?>" data-country-field="api_value" value="<?= h($c['api_value']) ?>" style="max-width:240px" />
            </td>
            <td>
              <select class="input" name="fulfillment_provider" form="<?= h($countryFormId) ?>" data-country-field="fulfillment_provider" style="max-width:130px">
                <option value="EFC" <?= strtoupper((string)$c['fulfillment_provider'])==='EFC'?'selected':'' ?>>EFC</option>
                <option value="QCARGO" <?= strtoupper((string)$c['fulfillment_provider'])==='QCARGO'?'selected':'' ?>>QCARGO</option>
                <option value="PICKPACK" <?= strtoupper((string)$c['fulfillment_provider'])==='PICKPACK'?'selected':'' ?>>Pick&Pack</option>
              </select>
            </td>
            <td class="muted">
              <input class="input" name="default_courier_code" form="<?= h($countryFormId) ?>" data-country-field="default_courier_code" value="<?= h($c['default_courier_code']) ?>" style="max-width:160px" />
            </td>
            <td>
              <input type="hidden" name="enabled" value="0" form="<?= h($countryFormId) ?>" />
              <label class="toggle" style="gap:8px">
                <input type="checkbox" name="enabled" form="<?= h($countryFormId) ?>" data-country-field="enabled" value="1" <?= ((int)$c['enabled']===1)?'checked':'' ?> />
                <span class="toggle-ui" aria-hidden="true"></span>
                <span class="muted small"><?= ((int)$c['enabled']===1)?'YES':'NO' ?></span>
              </label>
            </td>
            <td>
              <input type="hidden" name="show_on_home" value="0" form="<?= h($countryFormId) ?>" />
              <label class="toggle" style="gap:8px">
                <input type="checkbox" name="show_on_home" form="<?= h($countryFormId) ?>" data-country-field="show_on_home" value="1" <?= ((int)$c['show_on_home']===1)?'checked':'' ?> />
                <span class="toggle-ui" aria-hidden="true"></span>
                <span class="muted small"><?= ((int)$c['show_on_home']===1)?'YES':'NO' ?></span>
              </label>
            </td>
            <td class="right">
              <form method="post" id="<?= h($countryFormId) ?>" class="country-save-form" data-country-form="<?= h($c['code']) ?>" style="display:inline">
                <input type="hidden" name="op" value="update_country" />
                <input type="hidden" name="code" value="<?= h($c['code']) ?>" />
                <button class="btn btn-sm btn-ghost" type="submit">Save</button>
              </form>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</section>
<script>
window.addEventListener('load', function(){
  document.querySelectorAll('[data-country-row]').forEach(function(row){
    ['enabled', 'show_on_home'].forEach(function(field){
      const checkbox = row.querySelector('[data-country-field="' + field + '"]');
      if (!checkbox) return;
      const label = checkbox.closest('label');
      const text = label ? label.querySelector('.muted.small') : null;
      checkbox.addEventListener('change', function(){
        if (text) text.textContent = checkbox.checked ? 'YES' : 'NO';
      });
    });
  });
});
</script>
<section class="card" style="margin-top:16px">
  <div class="card-h">
    <div class="card-title">Cards (SKU list) + Stock</div>
    <div class="muted">Stock refreshed by cron/sync_stock.php</div>
  </div>

  <div class="table-wrap">
    <table class="table">
      <thead>
        <tr>
          <th>Country</th><th>SKU</th><th>Name</th><th>Active</th><th>Manual stock</th><th class="right">Last stock</th><th>Last stock at</th><th>Default / lead</th><th></th><th></th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($cards as $r): ?>
          <tr>
            <form method="post">
              <input type="hidden" name="op" value="update_card" />
              <input type="hidden" name="id" value="<?= (int)$r['id'] ?>" />
              <td>
                <select class="input" name="country" style="max-width:140px">
                  <?php foreach($countries as $c): ?>
                    <option value="<?= h($c['code']) ?>" <?= $r['country']===$c['code']?'selected':'' ?>><?= h($c['code']) ?></option>
                  <?php endforeach; ?>
                </select>
              </td>
              <td><input class="input" type="text" name="sku" value="<?= h($r['sku']) ?>" style="max-width:140px" /></td>
              <td><input class="input" type="text" name="name" value="<?= h($r['name']) ?>" style="max-width:180px" /></td>
              <td><input type="checkbox" name="active" value="1" <?= ((int)$r['active']===1)?'checked':'' ?> /></td>
              <td><input class="input" type="number" name="manual_stock_qty" value="<?= (int)($r['manual_stock_qty'] ?? 0) ?>" style="max-width:110px" /></td>
              <td class="right"><strong><?= (int)($r['last_stock_qty'] ?? 0) ?></strong></td>
              <td><?= h(dd($r['last_stock_at'])) ?></td>
              <td><input class="input" type="number" name="default_per_awb" value="<?= (int)($r['default_per_awb'] ?? 0) ?>" style="max-width:90px" /></td>
              <td class="right"><button class="btn btn-sm btn-ghost" type="submit">Save</button></td>
            </form>
            <td class="right">
              <form method="post" style="display:inline">
                <input type="hidden" name="op" value="delete_card" />
                <input type="hidden" name="id" value="<?= (int)$r['id'] ?>" />
                <button class="btn btn-sm btn-ghost" type="submit" onclick="return confirm('Delete card?')">Delete</button>
              </form>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <div class="sep"></div>

  <form class="row" method="post">
    <input type="hidden" name="op" value="save_card" />
    <select class="input" name="country" style="max-width:200px">
      <?php foreach($countries as $c): ?>
        <option value="<?= h($c['code']) ?>"><?= h($c['name']) ?> (<?= h($c['code']) ?>)</option>
      <?php endforeach; ?>
    </select>
    <input class="input" name="sku" placeholder="SKU" style="max-width:220px" />
    <input class="input" name="name" placeholder="Display name" style="max-width:240px" />
    <input class="input" type="number" name="manual_stock_qty" placeholder="Manual stock" style="max-width:130px" />
    <input class="input" type="number" name="default_per_awb" placeholder="Default / lead" style="max-width:130px" />
    <label class="toggle" style="gap:8px">
      <input type="checkbox" name="active" checked />
      <span>Active</span>
    </label>
    <button class="btn" type="submit">Save card</button>
    <a class="btn btn-ghost" href="/crons.php">Run stock cron</a>
  </form>
</section>
<?php endif; ?>
<?php require_once __DIR__ . '/_inc/layout_bottom.php'; ?>
