<?php
// app/helpers.php
function h($s): string { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

function base_path(): string {
  // subdomain docroot typically points to this folder, so base is empty.
  return '';
}

function url(string $path): string {
  $base = rtrim(base_path(), '/');
  return $base . $path;
}

function require_login(): void {
  if (session_status() === PHP_SESSION_NONE) session_start();
  if (empty($_SESSION['user_id']) || empty($_SESSION['company_id'])) {
    header("Location: " . url("/auth/login.php"));
    exit;
  }
}

function csrf_token(): string {
  if (session_status() === PHP_SESSION_NONE) session_start();
  if (empty($_SESSION['_csrf'])) {
    $_SESSION['_csrf'] = bin2hex(random_bytes(16));
  }
  return $_SESSION['_csrf'];
}

function csrf_check(): void {
  if (session_status() === PHP_SESSION_NONE) session_start();
  $t = $_POST['_csrf'] ?? '';
  if (!$t || empty($_SESSION['_csrf']) || !hash_equals($_SESSION['_csrf'], $t)) {
    http_response_code(419);
    die("CSRF token mismatch");
  }
}

/**
 * Render a date control as 3 selectpickers (day/month/year) + hidden YYYY-MM-DD.
 * This avoids native <input type="date"> inconsistencies and matches the requested UI.
 */
function render_date_selectpicker(string $name, ?string $value = null, bool $required = false): void {
  $value = $value ?: date('Y-m-d');
  $parts = explode('-', $value);
  $y = (int)($parts[0] ?? date('Y'));
  $m = (int)($parts[1] ?? date('m'));
  $d = (int)($parts[2] ?? date('d'));

  $months = [
    1=>'يناير',2=>'فبراير',3=>'مارس',4=>'أبريل',5=>'مايو',6=>'يونيو',
    7=>'يوليو',8=>'أغسطس',9=>'سبتمبر',10=>'أكتوبر',11=>'نوفمبر',12=>'ديسمبر'
  ];

  $curY = (int)date('Y');
  $startY = $curY - 7;
  $endY   = $curY + 7;
  $reqAttr = $required ? 'required' : '';

  ?>
  <div class="row g-2" data-date-group="<?= h($name) ?>">
    <div class="col-4">
      <select class="selectpicker w-100" data-style="btn-outline-secondary" data-size="8" name="<?= h($name) ?>_d" title="اليوم" <?= $reqAttr ?>>
        <?php for($i=1;$i<=31;$i++): $sel = ($i===$d)?'selected':''; ?>
          <option value="<?= $i ?>" <?= $sel ?>><?= $i ?></option>
        <?php endfor; ?>
      </select>
    </div>
    <div class="col-4">
      <select class="selectpicker w-100" data-style="btn-outline-secondary" data-size="8" name="<?= h($name) ?>_m" title="الشهر" <?= $reqAttr ?>>
        <?php foreach($months as $k=>$v): $sel = ($k===$m)?'selected':''; ?>
          <option value="<?= $k ?>" <?= $sel ?>><?= h($v) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-4">
      <select class="selectpicker w-100" data-style="btn-outline-secondary" data-size="8" name="<?= h($name) ?>_y" title="السنة" <?= $reqAttr ?>>
        <?php for($i=$endY;$i>=$startY;$i--): $sel = ($i===$y)?'selected':''; ?>
          <option value="<?= $i ?>" <?= $sel ?>><?= $i ?></option>
        <?php endfor; ?>
      </select>
    </div>
  </div>
  <input type="hidden" name="<?= h($name) ?>" id="<?= h($name) ?>" value="<?= h($value) ?>">
  <?php
}


function render_date_input(string $name, ?string $value = null, string $extraClass = ''): string {
  $v = $value ?: date('Y-m-d');
  $cls = trim('form-control datepick ' . $extraClass);
  return '<input type="text" name="'.h($name).'" value="'.h($v).'" class="'.$cls.'" autocomplete="off">';
}


function account_id_by_code(PDO $pdo, int $companyId, string $code): ?int {
  $st = $pdo->prepare("SELECT id FROM accounts WHERE company_id=? AND code=? LIMIT 1");
  $st->execute([$companyId, $code]);
  $id = $st->fetchColumn();
  return $id ? (int)$id : null;
}



function csrf_field(): string {
  return '<input type="hidden" name="_csrf" value="' . h(csrf_token()) . '">';
}


function csrf_bootstrap(): void {
  csrf_token();
}


function nf($n): string {
  return number_format((float)$n, 2);
}

function flash_set(string $message, string $type = 'success'): void {
  if (session_status() === PHP_SESSION_NONE) session_start();
  $_SESSION['_flash_toasts'] = $_SESSION['_flash_toasts'] ?? [];
  $_SESSION['_flash_toasts'][] = [
    'message' => $message,
    'type' => $type,
  ];
}

function flash_get_all(): array {
  if (session_status() === PHP_SESSION_NONE) session_start();
  $items = $_SESSION['_flash_toasts'] ?? [];
  unset($_SESSION['_flash_toasts']);
  return is_array($items) ? $items : [];
}

