<?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);

// كم يوم قبل البداية؟ (مثال: 1 يوم)
$daysBefore = 1;

// طلبات معتمدة تبدأ بعد X يوم ولم تُذكّر
$st = $pdo->prepare("
  SELECT id
  FROM leave_requests
  WHERE status='APPROVED'
    AND reminded_before_start_at IS NULL
    AND DATE(date_from) = DATE(DATE_ADD(CURDATE(), INTERVAL ? DAY))
  ORDER BY id ASC
  LIMIT 100
");
$st->execute([$daysBefore]);
$ids = $st->fetchAll(PDO::FETCH_COLUMN);

$sent = 0; $failed = 0;

foreach ($ids as $id) {
  $pdo->beginTransaction();
  try {
    $lock = $pdo->prepare("SELECT reminded_before_start_at FROM leave_requests WHERE id=? FOR UPDATE");
    $lock->execute([(int)$id]);
    $already = $lock->fetchColumn();
    if ($already) { $pdo->commit(); continue; }

    $res = send_leave_reminder_before_start($pdo, (int)$id, $daysBefore);
    if (!empty($res['ok'])) {
      $up = $pdo->prepare("UPDATE hr_leaves SET reminded_before_start_at=NOW() WHERE id=?");
      $up->execute([(int)$id]);
      $sent++;
    } else {
      $failed++;
    }

    $pdo->commit();
  } catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    $failed++;
  }
}

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