<?php
declare(strict_types=1);

require_once __DIR__ . '/../inc/db.php';
require_once __DIR__ . '/../inc/hr_leave_notifications.php';

$pdo = db();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$hours = 24;

$st = $pdo->prepare("
  SELECT id
  FROM leave_requests
  WHERE status='PENDING'
    AND created_at <= DATE_SUB(NOW(), INTERVAL ? HOUR)
    AND (reminded_pending_at IS NULL OR reminded_pending_at <= DATE_SUB(NOW(), INTERVAL 23 HOUR))
  ORDER BY id ASC
  LIMIT 50
");
$st->execute([$hours]);
$ids = $st->fetchAll(PDO::FETCH_COLUMN);

$sent = 0; $failed = 0;

foreach ($ids as $id) {
  $pdo->beginTransaction();
  try {
    $lock = $pdo->prepare("SELECT reminded_pending_at FROM leave_requests WHERE id=? FOR UPDATE");
    $lock->execute([(int)$id]);

    $res = send_leave_to_admin($pdo, (int)$id);
    if (!empty($res['ok'])) {
      $up = $pdo->prepare("UPDATE hr_leaves SET reminded_pending_at=NOW() WHERE id=?");
      $up->execute([(int)$id]);
      $sent++;
    } else {
      $failed++;
    }
    $pdo->commit();
  } catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    $failed++;
  }
}

echo "remind_pending sent={$sent} failed={$failed}\n";