<?php
require 'db.php';
require 'auth.php';
require_login();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $id = (int)($_POST['id'] ?? 0);
  $hari = (int)($_POST['hari'] ?? 3);
  
  if ($id > 0 && $hari > 0 && $hari <= 3) {
    // Get current return date first
    $stmt = $db->prepare("SELECT tanggal_kembali FROM peminjaman WHERE id = ? AND status = 'dipinjam'");
    $stmt->execute([$id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($row) {
      $tgl = new DateTime($row['tanggal_kembali']); 
      $tgl->add(new DateInterval('P'.$hari.'D'));
      $new_date = $tgl->format('Y-m-d');
      
      $update_stmt = $db->prepare("UPDATE peminjaman SET tanggal_kembali = ?, perpanjangan_count = perpanjangan_count + 1 WHERE id = ?");
      if ($update_stmt->execute([$new_date, $id])) {
        error_log("PERPANJANGAN: ID $id diperpanjang $hari hari menjadi $new_date oleh " . (current_user()['nama_lengkap'] ?? current_user()['username']));
        header('Location: index.php?success=extended');
      } else {
        header('Location: index.php?error=Gagal memperpanjang');
      }
    } else {
      header('Location: index.php?error=Data tidak ditemukan atau sudah dikembalikan');
    }
  } else {
    header('Location: index.php?error=Data tidak valid');
  }
} else {
  header('Location: index.php');
}
exit;
?>
