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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)($_POST['id'] ?? 0);
    
    if ($id > 0) {
        try {
            $current_date = date('Y-m-d');
            $current_time = date('H:i:s');
            
            $stmt = $db->prepare("UPDATE peminjaman SET 
                status = 'kembali', 
                tanggal_kembali_real = ?,
                waktu_kembali_real = ?
                WHERE id = ? AND status = 'dipinjam'");
            
            $result = $stmt->execute([$current_date, $current_time, $id]);
            
            if ($result && $stmt->rowCount() > 0) {
                header('Location: index.php?success=kembali');
            } else {
                header('Location: index.php?error=Gagal mengembalikan berkas atau berkas sudah dikembalikan');
            }
        } catch (PDOException $e) {
            header('Location: index.php?error=Error: ' . $e->getMessage());
        }
    } else {
        header('Location: index.php?error=ID tidak valid');
    }
} else {
    header('Location: index.php');
}
exit;
?>
