<?php
require __DIR__ . '/../Login/config.php';
require __DIR__ . '/../lib/lib_notify.php';
if (session_status() === PHP_SESSION_NONE) session_start();

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
  header('Location: ../Login/login.php'); exit;
}

$borrow_id = (int)($_GET['id'] ?? 0);
$new_status = $_GET['status'] ?? '';
$allowed = ['menunggu_konfirmasi','diterima','dipinjam','dikembalikan','ditolak'];
if ($borrow_id <= 0 || !in_array($new_status, $allowed, true)) {
  header('Location: borrow_requests.php'); exit;
}

// Opsi: FINE_PER_DAY dari config; fallback 1000
$DAILY_FINE = defined('FINE_PER_DAY') ? (int)FINE_PER_DAY : 1000;

$info = $pdo->prepare("
  SELECT br.user_id, br.book_item_id, br.tgl_pinjam, br.tgl_jatuh_tempo,
         b.judul AS judul_buku
  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.id = :id
");
$info->execute([':id'=>$borrow_id]);
$br = $info->fetch(PDO::FETCH_ASSOC);
if (!$br) { header('Location: borrow_requests.php'); exit; }

$user_id = (int)$br['user_id'];
$book_item_id = (int)$br['book_item_id'];

try {
  $pdo->beginTransaction();

  if ($new_status === 'dipinjam') {

    // JANGAN overwrite tanggal yg sudah di-set saat user pilih durasi
    if (empty($br['tgl_pinjam']) && empty($br['tgl_jatuh_tempo'])) {
      $today = $pdo->query("SELECT CURDATE()")->fetchColumn();
      $due   = $pdo->query("SELECT DATE_ADD(CURDATE(), INTERVAL 7 DAY)")->fetchColumn();
      $pdo->prepare("UPDATE borrowings SET status='dipinjam', tgl_pinjam=:t, tgl_jatuh_tempo=:d WHERE id=:id")
          ->execute([':t'=>$today, ':d'=>$due, ':id'=>$borrow_id]);
    } else {
      $pdo->prepare("UPDATE borrowings SET status='dipinjam' WHERE id=:id")
          ->execute([':id'=>$borrow_id]);
    }

    if ($book_item_id) {
      $pdo->prepare("UPDATE book_items SET status='dipinjam' WHERE id=:iid")
          ->execute([':iid'=>$book_item_id]);
    }

    // 🔔 NOTIF
    $dueDateStmt = $pdo->prepare("SELECT DATE_FORMAT(tgl_jatuh_tempo, '%d-%m-%Y') FROM borrowings WHERE id=:id");
    $dueDateStmt->execute([':id'=>$borrow_id]);
    $dueDate = $dueDateStmt->fetchColumn();

    $msg = "Peminjaman \"{$br['judul_buku']}\" telah AKTIF. Jatuh tempo: " . ($dueDate ?: '-');
    send_notification($pdo, $user_id, $borrow_id, 'STATUS_UPDATE', $msg);

  } elseif ($new_status === 'dikembalikan') {

    $today = $pdo->query("SELECT CURDATE()")->fetchColumn();

    // Hitung keterlambatan terhadap tgl_jatuh_tempo (>= 0)
    $lateDaysStmt = $pdo->prepare("
      SELECT GREATEST(DATEDIFF(:today, tgl_jatuh_tempo), 0)
      FROM borrowings WHERE id=:id
    ");
    $lateDaysStmt->execute([':today'=>$today, ':id'=>$borrow_id]);
    $lateDays = (int)$lateDaysStmt->fetchColumn();

    // Total denda = hari telat * tarif harian
    $denda = $lateDays * $DAILY_FINE;

    // Update status, tgl_kembali, dan denda
    $pdo->prepare("
      UPDATE borrowings
      SET status='dikembalikan',
          tgl_kembali=:tgl,
          denda=:d
      WHERE id=:id
    ")->execute([':tgl'=>$today, ':d'=>$denda, ':id'=>$borrow_id]);

    // ⭐ KWITANSI: set denda_bayar (sekali saja) + timestamp agar tombol "Kwitansi" muncul
    // Idempotent: hanya isi jika belum ada
    $pdo->prepare("
      UPDATE borrowings
      SET denda_bayar = CASE
            WHEN (denda_bayar IS NULL OR denda_bayar = 0) THEN :denda_bayar
            ELSE denda_bayar
          END,
          denda_bayar_tanggal = CASE
            WHEN (denda_bayar IS NULL OR denda_bayar = 0) THEN NOW()
            ELSE denda_bayar_tanggal
          END
      WHERE id = :id
    ")->execute([
      ':denda_bayar' => $denda,
      ':id' => $borrow_id
    ]);

    if ($book_item_id) {
      $pdo->prepare("UPDATE book_items SET status='tersedia' WHERE id=:iid")
          ->execute([':iid'=>$book_item_id]);
    }

    // 🔔 NOTIF
    $msg = $lateDays > 0
      ? "Buku \"{$br['judul_buku']}\" dikembalikan. Denda: Rp " . number_format($denda, 0, ',', '.') . " ({$lateDays} hari)."
      : "Terima kasih! Buku \"{$br['judul_buku']}\" telah dikembalikan.";
    send_notification($pdo, $user_id, $borrow_id, 'STATUS_UPDATE', $msg);

  } elseif ($new_status === 'ditolak') {

    $pdo->prepare("UPDATE borrowings SET status='ditolak' WHERE id=:id")
        ->execute([':id'=>$borrow_id]);

    if ($book_item_id) {
      $pdo->prepare("UPDATE book_items SET status='tersedia' WHERE id=:iid")
          ->execute([':iid'=>$book_item_id]);
    }

    // 🔔 NOTIF
    $msg = "Permintaan peminjaman \"{$br['judul_buku']}\" DITOLAK admin.";
    send_notification($pdo, $user_id, $borrow_id, 'STATUS_UPDATE', $msg);

  } else {
    // menunggu_konfirmasi / diterima
    $pdo->prepare("UPDATE borrowings SET status=:s WHERE id=:id")
        ->execute([':s'=>$new_status, ':id'=>$borrow_id]);

    // 🔔 NOTIF
    if ($new_status === 'diterima') {
      $msg = "Permintaan peminjaman \"{$br['judul_buku']}\" DITERIMA. Silakan ambil buku di perpustakaan.";
    } else {
      $msg = "Status peminjaman \"{$br['judul_buku']}\" diperbarui: {$new_status}.";
    }
    send_notification($pdo, $user_id, $borrow_id, 'STATUS_UPDATE', $msg);
  }

  $pdo->commit();
} catch (Exception $e) {
  $pdo->rollBack();
  // (opsional) log error
}

header('Location: borrow_requests.php'); exit;
