<?php
session_start();
require '../Login/config.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: ../Login/login.php");
    exit;
}

$user_id = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: books.php");
    exit;
}

$book_id = intval($_POST['book_id'] ?? 0);
$durasi  = intval($_POST['durasi'] ?? 0);

if ($book_id <= 0) { header('Location: books.php'); exit; }
if ($durasi < 1 || $durasi > 7) {
    header("Location: detail.php?id=$book_id&error=Durasi tidak valid (1–7 hari)");
    exit;
}

/* ===== Validasi & simpan file bukti ===== */
if (!isset($_FILES['bukti']) || $_FILES['bukti']['error'] !== UPLOAD_ERR_OK) {
    header("Location: detail.php?id=$book_id&error=Unggah file bukti diperlukan");
    exit;
}
$maxSize = 3 * 1024 * 1024; // 3 MB
$allowed = ['image/png','image/jpeg','image/jpg','image/gif','application/pdf'];
if ($_FILES['bukti']['size'] > $maxSize) {
    header("Location: detail.php?id=$book_id&error=Ukuran file maksimal 3 MB");
    exit;
}
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime  = $finfo->file($_FILES['bukti']['tmp_name']);
if (!in_array($mime, $allowed, true)) {
    header("Location: detail.php?id=$book_id&error=Format file harus gambar atau PDF");
    exit;
}

$uploadRoot = __DIR__ . '/../Uploads';
if (!is_dir($uploadRoot)) { @mkdir($uploadRoot, 0775, true); }
$proofDir = $uploadRoot . '/borrow-proofs';
if (!is_dir($proofDir)) { @mkdir($proofDir, 0775, true); }

$ext = ($mime === 'application/pdf') ? 'pdf' : (pathinfo($_FILES['bukti']['name'], PATHINFO_EXTENSION) ?: 'bin');
$ext = preg_replace('/[^a-zA-Z0-9]/','', $ext);
$filename = 'proof_'.$user_id.'_'.$book_id.'_'.time().'.'.$ext;
$destAbs  = $proofDir . '/' . $filename;

if (!move_uploaded_file($_FILES['bukti']['tmp_name'], $destAbs)) {
    header("Location: detail.php?id=$book_id&error=Gagal menyimpan file bukti");
    exit;
}
$destRel = '../Uploads/borrow-proofs/' . $filename;

/* ===== Cek duplikat pinjaman aktif ===== */
$cek_duplikat = $pdo->prepare("
    SELECT COUNT(*)
    FROM borrowings br
    JOIN book_items bi ON br.book_item_id = bi.id
    WHERE br.user_id = :uid
      AND bi.book_id = :bid
      AND br.status IN ('dipinjam','menunggu_konfirmasi')
");
$cek_duplikat->execute([':uid'=>$user_id, ':bid'=>$book_id]);
if ($cek_duplikat->fetchColumn() > 0) {
    @unlink($destAbs);
    header("Location: detail.php?id=$book_id&error=Kamu sudah meminjam buku ini");
    exit;
}

/* ===== Ambil 1 eksemplar tersedia ===== */
$stmt_item = $pdo->prepare("
    SELECT id FROM book_items
    WHERE book_id = :bid AND status = 'tersedia'
    LIMIT 1
");
$stmt_item->execute([':bid'=>$book_id]);
$book_item_id = $stmt_item->fetchColumn();
if (!$book_item_id) {
    @unlink($destAbs);
    header("Location: detail.php?id=$book_id&error=Stok buku habis");
    exit;
}

try {
    $pdo->beginTransaction();

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

    // Tanggal pinjam & jatuh tempo
    $today = $pdo->query("SELECT CURDATE()")->fetchColumn();
    $stmt_due = $pdo->prepare("SELECT DATE_ADD(:t, INTERVAL :d DAY)");
    $stmt_due->execute([':t'=>$today, ':d'=>$durasi]);
    $due = $stmt_due->fetchColumn();

    // Simpan borrowings
    $insert = $pdo->prepare("
        INSERT INTO borrowings (user_id, book_item_id, tgl_pinjam, tgl_jatuh_tempo, bukti_path, denda, status)
        VALUES (:uid, :iid, :tgl, :due, :bukti, 0, 'menunggu_konfirmasi')
    ");
    $insert->execute([
        ':uid'=>$user_id,
        ':iid'=>$book_item_id,
        ':tgl'=>$today,
        ':due'=>$due,
        ':bukti'=>$destRel
    ]);

    $pdo->commit();
    header("Location: detail.php?id=$book_id&success=Permintaan menunggu konfirmasi. Jatuh tempo: $due");
    exit;

} catch (Exception $e) {
    $pdo->rollBack();
    @unlink($destAbs);
    header("Location: detail.php?id=$book_id&error=Gagal memproses peminjaman");
    exit;
}
