<?php
require __DIR__ . '/../Login/config.php';
require __DIR__ . '/../Pages/lib_notify.php';

/* H-1 */
$h1 = $pdo->query("
  SELECT br.id AS borrow_id, br.user_id, b.judul
  FROM borrowings br
  JOIN book_items bi ON br.book_item_id = bi.id
  JOIN books b ON bi.book_id = b.id
  WHERE br.status='dipinjam'
    AND br.tgl_jatuh_tempo = DATE_ADD(CURDATE(), INTERVAL 1 DAY)
")->fetchAll(PDO::FETCH_ASSOC);

foreach ($h1 as $r) {
  $msg = "Pengingat: Besok jatuh tempo \"{$r['judul']}\". Mohon kembalikan tepat waktu.";
  send_notification($pdo, (int)$r['user_id'], (int)$r['borrow_id'], 'REMINDER_H1', $msg, date('Y-m-d'));
}

/* Overdue harian */
$over = $pdo->query("
  SELECT br.id AS borrow_id, br.user_id, b.judul,
         GREATEST(DATEDIFF(CURDATE(), br.tgl_jatuh_tempo), 0) AS late_days
  FROM borrowings br
  JOIN book_items bi ON br.book_item_id = bi.id
  JOIN books b ON bi.book_id = b.id
  WHERE br.status='dipinjam'
    AND br.tgl_jatuh_tempo IS NOT NULL
    AND br.tgl_jatuh_tempo < CURDATE()
")->fetchAll(PDO::FETCH_ASSOC);

foreach ($over as $r) {
  $late = (int)$r['late_days'];
  $denda = $late * 1000;
  $msg = "Telat {$late} hari untuk \"{$r['judul']}\". Denda Rp1.000/hari (total sementara Rp " . number_format($denda,0,',','.') . ").";
  send_notification($pdo, (int)$r['user_id'], (int)$r['borrow_id'], 'REMINDER_OVERDUE', $msg, date('Y-m-d'));
}
