<?php
// modules/peminjaman_alat.php
// Modul Peminjaman Alat Antar Unit - RS BaliMed Denpasar

declare(strict_types=1);

if (!function_exists('e')) {
    function e($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (function_exists('checkAuth')) {
    checkAuth();
}

$conn = getConnection();

function pa_table_exists(mysqli $conn, string $table): bool
{
    $safe = $conn->real_escape_string($table);
    $res = $conn->query("SHOW TABLES LIKE '{$safe}'");
    return $res && $res->num_rows > 0;
}

function pa_column_exists(mysqli $conn, string $table, string $column): bool
{
    $safeTable = $conn->real_escape_string($table);
    $safeColumn = $conn->real_escape_string($column);
    $res = $conn->query("SHOW COLUMNS FROM `{$safeTable}` LIKE '{$safeColumn}'");
    return $res && $res->num_rows > 0;
}

function pa_ensure_schema(mysqli $conn): void
{
    $conn->query("CREATE TABLE IF NOT EXISTS alat_unit_loans (
        id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        loan_number VARCHAR(40) NOT NULL UNIQUE,
        tool_name VARCHAR(180) NOT NULL,
        tool_type ENUM('medis','nonmedis') NOT NULL DEFAULT 'medis',
        serial_number VARCHAR(120) NULL,
        condition_before VARCHAR(120) NULL,
        borrower_unit_id INT NULL,
        borrower_unit_name VARCHAR(160) NULL,
        lender_unit_id INT NULL,
        lender_unit_name VARCHAR(160) NULL,
        borrower_name VARCHAR(160) NOT NULL,
        loan_date DATE NOT NULL,
        planned_return_date DATE NULL,
        status ENUM('dipinjam','dikembalikan') NOT NULL DEFAULT 'dipinjam',
        return_date DATE NULL,
        receiver_name VARCHAR(160) NULL,
        handover_name VARCHAR(160) NULL,
        condition_after VARCHAR(120) NULL,
        notes TEXT NULL,
        created_by INT NULL,
        returned_by INT NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_status (status),
        INDEX idx_loan_date (loan_date),
        INDEX idx_borrower_unit (borrower_unit_id),
        INDEX idx_lender_unit (lender_unit_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

    $columns = [
        'borrower_unit_name' => "ALTER TABLE alat_unit_loans ADD COLUMN borrower_unit_name VARCHAR(160) NULL AFTER borrower_unit_id",
        'lender_unit_name' => "ALTER TABLE alat_unit_loans ADD COLUMN lender_unit_name VARCHAR(160) NULL AFTER lender_unit_id",
        'planned_return_date' => "ALTER TABLE alat_unit_loans ADD COLUMN planned_return_date DATE NULL AFTER loan_date",
        'condition_after' => "ALTER TABLE alat_unit_loans ADD COLUMN condition_after VARCHAR(120) NULL AFTER handover_name",
        'notes' => "ALTER TABLE alat_unit_loans ADD COLUMN notes TEXT NULL AFTER condition_after",
        'returned_by' => "ALTER TABLE alat_unit_loans ADD COLUMN returned_by INT NULL AFTER created_by",
    ];

    foreach ($columns as $column => $sql) {
        if (!pa_column_exists($conn, 'alat_unit_loans', $column)) {
            @$conn->query($sql);
        }
    }
}

function pa_get_units(mysqli $conn): array
{
    $units = [];
    if (function_exists('getUnits')) {
        $raw = getUnits();
        if (is_array($raw)) {
            foreach ($raw as $unit) {
                $id = (int)($unit['id'] ?? 0);
                $name = trim((string)($unit['name'] ?? $unit['unit_name'] ?? ''));
                if ($id > 0 && $name !== '') {
                    $units[] = ['id' => $id, 'name' => $name];
                }
            }
        }
    }

    if (!$units && pa_table_exists($conn, 'units')) {
        $res = $conn->query("SELECT id, name FROM units WHERE COALESCE(is_active, 1) = 1 ORDER BY name ASC");
        if ($res) {
            while ($row = $res->fetch_assoc()) {
                $units[] = ['id' => (int)$row['id'], 'name' => (string)$row['name']];
            }
        }
    }

    return $units;
}

function pa_unit_name_from_id(array $units, int $id): string
{
    foreach ($units as $unit) {
        if ((int)$unit['id'] === $id) {
            return (string)$unit['name'];
        }
    }
    return '';
}

function pa_flash(string $type, string $message): void
{
    $_SESSION['pa_flash'] = ['type' => $type, 'message' => $message];
}

function pa_redirect(string $extra = ''): void
{
    $url = 'index.php?module=peminjaman_alat' . $extra;
    echo "<script>window.location.href='" . e($url) . "';</script>";
    exit;
}

function pa_generate_loan_number(mysqli $conn): string
{
    $prefix = 'PA/' . date('Ym') . '/';
    $like = $prefix . '%';
    $stmt = $conn->prepare("SELECT COUNT(*) AS total FROM alat_unit_loans WHERE loan_number LIKE ?");
    $stmt->bind_param('s', $like);
    $stmt->execute();
    $total = (int)($stmt->get_result()->fetch_assoc()['total'] ?? 0) + 1;
    $stmt->close();
    return $prefix . str_pad((string)$total, 4, '0', STR_PAD_LEFT);
}

function pa_status_badge(string $status): string
{
    if ($status === 'dikembalikan') {
        return '<span class="inline-flex items-center rounded-full bg-emerald-100 px-3 py-1 text-xs font-semibold text-emerald-700"><i class="fas fa-check-circle mr-1"></i>Dikembalikan</span>';
    }
    return '<span class="inline-flex items-center rounded-full bg-amber-100 px-3 py-1 text-xs font-semibold text-amber-700"><i class="fas fa-clock mr-1"></i>Dipinjam</span>';
}

pa_ensure_schema($conn);
$units = pa_get_units($conn);
$action = $_GET['action'] ?? 'list';
$userId = (int)($_SESSION['user_id'] ?? $_SESSION['user']['id'] ?? 0);
$userRole = strtolower((string)($_SESSION['user_role'] ?? $_SESSION['user']['role'] ?? 'viewer'));
$isAdminLike = in_array($userRole, ['admin', 'superadmin'], true);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postAction = $_POST['form_action'] ?? '';

    if ($postAction === 'create_loan') {
        $toolName = trim((string)($_POST['tool_name'] ?? ''));
        $toolType = ($_POST['tool_type'] ?? 'medis') === 'nonmedis' ? 'nonmedis' : 'medis';
        $serialNumber = trim((string)($_POST['serial_number'] ?? ''));
        $conditionBefore = trim((string)($_POST['condition_before'] ?? ''));
        $borrowerUnitId = (int)($_POST['borrower_unit_id'] ?? 0);
        $lenderUnitId = (int)($_POST['lender_unit_id'] ?? 0);
        $borrowerName = trim((string)($_POST['borrower_name'] ?? ''));
        $loanDate = trim((string)($_POST['loan_date'] ?? date('Y-m-d')));
        $plannedReturnDate = trim((string)($_POST['planned_return_date'] ?? ''));
        $notes = trim((string)($_POST['notes'] ?? ''));

        $borrowerUnitName = pa_unit_name_from_id($units, $borrowerUnitId);
        $lenderUnitName = pa_unit_name_from_id($units, $lenderUnitId);

        if ($toolName === '' || $borrowerName === '' || $borrowerUnitId <= 0 || $lenderUnitId <= 0 || $loanDate === '') {
            pa_flash('error', 'Data wajib belum lengkap. Isi nama alat, unit peminjam, unit pemberi, nama peminjam, dan tanggal peminjaman.');
            pa_redirect('&action=create');
        }

        $loanNumber = pa_generate_loan_number($conn);
        $plannedReturnDateDb = $plannedReturnDate !== '' ? $plannedReturnDate : null;
        $serialDb = $serialNumber !== '' ? $serialNumber : null;
        $conditionDb = $conditionBefore !== '' ? $conditionBefore : null;
        $notesDb = $notes !== '' ? $notes : null;

        $stmt = $conn->prepare("INSERT INTO alat_unit_loans
            (loan_number, tool_name, tool_type, serial_number, condition_before, borrower_unit_id, borrower_unit_name, lender_unit_id, lender_unit_name, borrower_name, loan_date, planned_return_date, notes, created_by)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param(
            'sssssisisssssi',
            $loanNumber,
            $toolName,
            $toolType,
            $serialDb,
            $conditionDb,
            $borrowerUnitId,
            $borrowerUnitName,
            $lenderUnitId,
            $lenderUnitName,
            $borrowerName,
            $loanDate,
            $plannedReturnDateDb,
            $notesDb,
            $userId
        );

        if ($stmt->execute()) {
            if (function_exists('logActivity')) {
                logActivity('create', 'alat_unit_loans', (int)$conn->insert_id, 'Membuat peminjaman alat: ' . $loanNumber);
            }
            pa_flash('success', 'Peminjaman alat berhasil disimpan. Nomor: ' . $loanNumber);
            $stmt->close();
            pa_redirect();
        }

        $err = $stmt->error;
        $stmt->close();
        pa_flash('error', 'Gagal menyimpan peminjaman: ' . $err);
        pa_redirect('&action=create');
    }

    if ($postAction === 'return_loan') {
        $id = (int)($_POST['id'] ?? 0);
        $returnDate = trim((string)($_POST['return_date'] ?? date('Y-m-d')));
        $receiverName = trim((string)($_POST['receiver_name'] ?? ''));
        $handoverName = trim((string)($_POST['handover_name'] ?? ''));
        $conditionAfter = trim((string)($_POST['condition_after'] ?? ''));
        $notes = trim((string)($_POST['notes'] ?? ''));

        if ($id <= 0 || $returnDate === '' || $receiverName === '' || $handoverName === '') {
            pa_flash('error', 'Data pengembalian belum lengkap. Isi tanggal pengembalian, nama penerima, dan nama yang menyerahkan.');
            pa_redirect();
        }

        $conditionAfterDb = $conditionAfter !== '' ? $conditionAfter : null;
        $notesDb = $notes !== '' ? $notes : null;

        $stmt = $conn->prepare("UPDATE alat_unit_loans
            SET status = 'dikembalikan', return_date = ?, receiver_name = ?, handover_name = ?, condition_after = ?, notes = COALESCE(?, notes), returned_by = ?
            WHERE id = ? AND status = 'dipinjam'");
        $stmt->bind_param('sssssii', $returnDate, $receiverName, $handoverName, $conditionAfterDb, $notesDb, $userId, $id);

        if ($stmt->execute()) {
            if ($stmt->affected_rows > 0) {
                if (function_exists('logActivity')) {
                    logActivity('update', 'alat_unit_loans', $id, 'Mengembalikan alat pinjaman');
                }
                pa_flash('success', 'Pengembalian alat berhasil disimpan.');
            } else {
                pa_flash('error', 'Data tidak ditemukan atau alat sudah dikembalikan sebelumnya.');
            }
            $stmt->close();
            pa_redirect();
        }

        $err = $stmt->error;
        $stmt->close();
        pa_flash('error', 'Gagal menyimpan pengembalian: ' . $err);
        pa_redirect();
    }

    if ($postAction === 'delete_loan' && $isAdminLike) {
        $id = (int)($_POST['id'] ?? 0);
        if ($id > 0) {
            $stmt = $conn->prepare("DELETE FROM alat_unit_loans WHERE id = ?");
            $stmt->bind_param('i', $id);
            if ($stmt->execute()) {
                if (function_exists('logActivity')) {
                    logActivity('delete', 'alat_unit_loans', $id, 'Menghapus data peminjaman alat');
                }
                pa_flash('success', 'Data peminjaman berhasil dihapus.');
            } else {
                pa_flash('error', 'Gagal menghapus data: ' . $stmt->error);
            }
            $stmt->close();
        }
        pa_redirect();
    }
}

$filterStatus = $_GET['status'] ?? 'all';
$filterType = $_GET['type'] ?? 'all';
$filterUnit = (int)($_GET['unit_id'] ?? 0);
$search = trim((string)($_GET['q'] ?? ''));

$where = [];
$params = [];
$types = '';

if (in_array($filterStatus, ['dipinjam', 'dikembalikan'], true)) {
    $where[] = 'l.status = ?';
    $params[] = $filterStatus;
    $types .= 's';
}

if (in_array($filterType, ['medis', 'nonmedis'], true)) {
    $where[] = 'l.tool_type = ?';
    $params[] = $filterType;
    $types .= 's';
}

if ($filterUnit > 0) {
    $where[] = '(l.borrower_unit_id = ? OR l.lender_unit_id = ?)';
    $params[] = $filterUnit;
    $params[] = $filterUnit;
    $types .= 'ii';
}

if ($search !== '') {
    $where[] = '(l.loan_number LIKE ? OR l.tool_name LIKE ? OR l.serial_number LIKE ? OR l.borrower_name LIKE ? OR l.receiver_name LIKE ? OR l.handover_name LIKE ?)';
    $like = '%' . $search . '%';
    for ($i = 0; $i < 6; $i++) {
        $params[] = $like;
        $types .= 's';
    }
}

$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';
$sql = "SELECT l.* FROM alat_unit_loans l {$whereSql} ORDER BY FIELD(l.status, 'dipinjam', 'dikembalikan'), l.loan_date DESC, l.id DESC LIMIT 300";
$stmt = $conn->prepare($sql);
if ($params) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$loans = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$stats = ['dipinjam' => 0, 'dikembalikan' => 0, 'total' => 0, 'overdue' => 0];
$resStats = $conn->query("SELECT status, COUNT(*) total FROM alat_unit_loans GROUP BY status");
if ($resStats) {
    while ($row = $resStats->fetch_assoc()) {
        $stats[$row['status']] = (int)$row['total'];
        $stats['total'] += (int)$row['total'];
    }
}
$resOverdue = $conn->query("SELECT COUNT(*) total FROM alat_unit_loans WHERE status='dipinjam' AND planned_return_date IS NOT NULL AND planned_return_date < CURDATE()");
if ($resOverdue) {
    $stats['overdue'] = (int)($resOverdue->fetch_assoc()['total'] ?? 0);
}

$flash = $_SESSION['pa_flash'] ?? null;
unset($_SESSION['pa_flash']);
?>

<div class="max-w-7xl mx-auto space-y-6">
    <div class="relative overflow-hidden rounded-3xl bg-gradient-to-br from-slate-900 via-indigo-900 to-blue-900 p-6 text-white shadow-2xl">
        <div class="absolute right-0 top-0 h-40 w-40 rounded-full bg-cyan-400/20 blur-3xl"></div>
        <div class="absolute bottom-0 left-1/3 h-32 w-32 rounded-full bg-fuchsia-400/20 blur-3xl"></div>
        <div class="relative flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
            <div>
                <p class="text-xs uppercase tracking-[0.3em] text-cyan-200">Inventory Movement</p>
                <h1 class="mt-2 text-2xl md:text-3xl font-bold">Peminjaman Alat Antar Unit</h1>
                <p class="mt-2 max-w-2xl text-sm text-blue-100">Pencatatan alat medis/nonmedis yang dipinjam antar unit, status pengembalian, penerima, penyerah, dan kondisi alat.</p>
            </div>
            <div class="flex flex-wrap gap-2">
                <a href="index.php?module=peminjaman_alat" class="rounded-xl bg-white/10 px-4 py-2 text-sm font-semibold hover:bg-white/20 transition"><i class="fas fa-list mr-2"></i>Daftar</a>
                <a href="index.php?module=peminjaman_alat&action=create" class="rounded-xl bg-cyan-400 px-4 py-2 text-sm font-bold text-slate-900 hover:bg-cyan-300 transition"><i class="fas fa-plus mr-2"></i>Input Peminjaman</a>
            </div>
        </div>
    </div>

    <?php if ($flash): ?>
        <div class="rounded-2xl border <?= $flash['type'] === 'success' ? 'border-emerald-200 bg-emerald-50 text-emerald-700' : 'border-rose-200 bg-rose-50 text-rose-700' ?> px-5 py-4 shadow-sm">
            <i class="fas <?= $flash['type'] === 'success' ? 'fa-check-circle' : 'fa-triangle-exclamation' ?> mr-2"></i><?= e($flash['message']) ?>
        </div>
    <?php endif; ?>

    <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div class="rounded-2xl bg-white p-5 shadow border border-slate-100">
            <p class="text-xs uppercase text-slate-400">Total Transaksi</p>
            <p class="mt-2 text-3xl font-bold text-slate-800"><?= number_format($stats['total'], 0, ',', '.') ?></p>
        </div>
        <div class="rounded-2xl bg-white p-5 shadow border border-amber-100">
            <p class="text-xs uppercase text-amber-500">Sedang Dipinjam</p>
            <p class="mt-2 text-3xl font-bold text-amber-600"><?= number_format($stats['dipinjam'], 0, ',', '.') ?></p>
        </div>
        <div class="rounded-2xl bg-white p-5 shadow border border-emerald-100">
            <p class="text-xs uppercase text-emerald-500">Dikembalikan</p>
            <p class="mt-2 text-3xl font-bold text-emerald-600"><?= number_format($stats['dikembalikan'], 0, ',', '.') ?></p>
        </div>
        <div class="rounded-2xl bg-white p-5 shadow border border-rose-100">
            <p class="text-xs uppercase text-rose-500">Lewat Rencana</p>
            <p class="mt-2 text-3xl font-bold text-rose-600"><?= number_format($stats['overdue'], 0, ',', '.') ?></p>
        </div>
    </div>

    <?php if ($action === 'create'): ?>
        <div class="rounded-3xl bg-white p-6 shadow-xl border border-slate-100">
            <div class="mb-5 flex items-center justify-between gap-3">
                <div>
                    <h2 class="text-xl font-bold text-slate-800">Form Peminjaman Alat</h2>
                    <p class="text-sm text-slate-500">Isi data alat dan unit yang terlibat.</p>
                </div>
                <a href="index.php?module=peminjaman_alat" class="rounded-xl border border-slate-200 px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-50"><i class="fas fa-arrow-left mr-2"></i>Kembali</a>
            </div>
            <form method="post" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <input type="hidden" name="form_action" value="create_loan">
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-1">Nama Alat *</label>
                    <input name="tool_name" required class="w-full rounded-xl border border-slate-200 px-4 py-3 focus:border-blue-500 focus:ring-blue-500" placeholder="Contoh: Infus Pump, Kursi Roda, Monitor Pasien">
                </div>
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-1">Jenis *</label>
                    <select name="tool_type" required class="w-full rounded-xl border border-slate-200 px-4 py-3 focus:border-blue-500 focus:ring-blue-500">
                        <option value="medis">Medis</option>
                        <option value="nonmedis">Nonmedis</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-1">Nomor Seri</label>
                    <input name="serial_number" class="w-full rounded-xl border border-slate-200 px-4 py-3 focus:border-blue-500 focus:ring-blue-500" placeholder="Nomor seri/inventaris bila ada">
                </div>
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-1">Kondisi Saat Dipinjam</label>
                    <select name="condition_before" class="w-full rounded-xl border border-slate-200 px-4 py-3 focus:border-blue-500 focus:ring-blue-500">
                        <option value="Baik">Baik</option>
                        <option value="Cukup">Cukup</option>
                        <option value="Rusak Ringan">Rusak Ringan</option>
                        <option value="Perlu Dicek">Perlu Dicek</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-1">Unit Peminjam *</label>
                    <select name="borrower_unit_id" required class="w-full rounded-xl border border-slate-200 px-4 py-3 focus:border-blue-500 focus:ring-blue-500">
                        <option value="">-- Pilih Unit --</option>
                        <?php foreach ($units as $unit): ?>
                            <option value="<?= (int)$unit['id'] ?>"><?= e($unit['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-1">Unit Pemberi *</label>
                    <select name="lender_unit_id" required class="w-full rounded-xl border border-slate-200 px-4 py-3 focus:border-blue-500 focus:ring-blue-500">
                        <option value="">-- Pilih Unit --</option>
                        <?php foreach ($units as $unit): ?>
                            <option value="<?= (int)$unit['id'] ?>"><?= e($unit['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-1">Nama Peminjam *</label>
                    <input name="borrower_name" required class="w-full rounded-xl border border-slate-200 px-4 py-3 focus:border-blue-500 focus:ring-blue-500" placeholder="Nama staf yang meminjam">
                </div>
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-1">Tanggal Peminjaman *</label>
                    <input type="date" name="loan_date" value="<?= date('Y-m-d') ?>" required class="w-full rounded-xl border border-slate-200 px-4 py-3 focus:border-blue-500 focus:ring-blue-500">
                </div>
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-1">Rencana Tanggal Pengembalian</label>
                    <input type="date" name="planned_return_date" class="w-full rounded-xl border border-slate-200 px-4 py-3 focus:border-blue-500 focus:ring-blue-500">
                </div>
                <div class="md:col-span-2">
                    <label class="block text-sm font-semibold text-slate-700 mb-1">Keterangan</label>
                    <textarea name="notes" rows="3" class="w-full rounded-xl border border-slate-200 px-4 py-3 focus:border-blue-500 focus:ring-blue-500" placeholder="Catatan tambahan bila ada"></textarea>
                </div>
                <div class="md:col-span-2 flex justify-end gap-2">
                    <a href="index.php?module=peminjaman_alat" class="rounded-xl border border-slate-200 px-5 py-3 text-sm font-semibold text-slate-600 hover:bg-slate-50">Batal</a>
                    <button class="rounded-xl bg-gradient-to-r from-blue-600 to-indigo-600 px-5 py-3 text-sm font-bold text-white shadow-lg hover:from-blue-700 hover:to-indigo-700"><i class="fas fa-save mr-2"></i>Simpan Peminjaman</button>
                </div>
            </form>
        </div>
    <?php else: ?>
        <div class="rounded-3xl bg-white p-5 shadow-xl border border-slate-100">
            <form method="get" class="grid grid-cols-1 md:grid-cols-5 gap-3">
                <input type="hidden" name="module" value="peminjaman_alat">
                <div class="md:col-span-2">
                    <label class="block text-xs font-semibold text-slate-500 mb-1">Cari</label>
                    <input name="q" value="<?= e($search) ?>" class="w-full rounded-xl border border-slate-200 px-4 py-2.5" placeholder="No, alat, seri, nama">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-500 mb-1">Status</label>
                    <select name="status" class="w-full rounded-xl border border-slate-200 px-4 py-2.5">
                        <option value="all">Semua</option>
                        <option value="dipinjam" <?= $filterStatus === 'dipinjam' ? 'selected' : '' ?>>Dipinjam</option>
                        <option value="dikembalikan" <?= $filterStatus === 'dikembalikan' ? 'selected' : '' ?>>Dikembalikan</option>
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-500 mb-1">Jenis</label>
                    <select name="type" class="w-full rounded-xl border border-slate-200 px-4 py-2.5">
                        <option value="all">Semua</option>
                        <option value="medis" <?= $filterType === 'medis' ? 'selected' : '' ?>>Medis</option>
                        <option value="nonmedis" <?= $filterType === 'nonmedis' ? 'selected' : '' ?>>Nonmedis</option>
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-500 mb-1">Unit</label>
                    <select name="unit_id" class="w-full rounded-xl border border-slate-200 px-4 py-2.5">
                        <option value="0">Semua Unit</option>
                        <?php foreach ($units as $unit): ?>
                            <option value="<?= (int)$unit['id'] ?>" <?= $filterUnit === (int)$unit['id'] ? 'selected' : '' ?>><?= e($unit['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="md:col-span-5 flex justify-end gap-2">
                    <a href="index.php?module=peminjaman_alat" class="rounded-xl border border-slate-200 px-4 py-2.5 text-sm font-semibold text-slate-600 hover:bg-slate-50">Reset</a>
                    <button class="rounded-xl bg-slate-900 px-4 py-2.5 text-sm font-bold text-white hover:bg-slate-800"><i class="fas fa-filter mr-2"></i>Terapkan</button>
                </div>
            </form>
        </div>

        <div class="rounded-3xl bg-white shadow-xl border border-slate-100 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-slate-100">
                    <thead class="bg-slate-50">
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-bold uppercase tracking-wider text-slate-500">No</th>
                        <th class="px-4 py-3 text-left text-xs font-bold uppercase tracking-wider text-slate-500">Alat</th>
                        <th class="px-4 py-3 text-left text-xs font-bold uppercase tracking-wider text-slate-500">Unit</th>
                        <th class="px-4 py-3 text-left text-xs font-bold uppercase tracking-wider text-slate-500">Peminjaman</th>
                        <th class="px-4 py-3 text-left text-xs font-bold uppercase tracking-wider text-slate-500">Pengembalian</th>
                        <th class="px-4 py-3 text-left text-xs font-bold uppercase tracking-wider text-slate-500">Status</th>
                        <th class="px-4 py-3 text-right text-xs font-bold uppercase tracking-wider text-slate-500">Aksi</th>
                    </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100 bg-white">
                    <?php if (!$loans): ?>
                        <tr><td colspan="7" class="px-4 py-10 text-center text-slate-500">Belum ada data peminjaman alat.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($loans as $row): ?>
                        <?php
                        $isOverdue = $row['status'] === 'dipinjam' && !empty($row['planned_return_date']) && $row['planned_return_date'] < date('Y-m-d');
                        ?>
                        <tr class="hover:bg-slate-50/70">
                            <td class="px-4 py-4 align-top">
                                <div class="font-bold text-slate-800"><?= e($row['loan_number']) ?></div>
                                <div class="text-xs text-slate-400">#<?= (int)$row['id'] ?></div>
                            </td>
                            <td class="px-4 py-4 align-top">
                                <div class="font-semibold text-slate-800"><?= e($row['tool_name']) ?></div>
                                <div class="mt-1 text-xs text-slate-500"><span class="rounded-full bg-blue-50 px-2 py-1 font-semibold text-blue-700"><?= e(strtoupper($row['tool_type'])) ?></span></div>
                                <div class="mt-1 text-xs text-slate-500">Seri: <?= e($row['serial_number'] ?: '-') ?></div>
                                <div class="mt-1 text-xs text-slate-500">Kondisi awal: <?= e($row['condition_before'] ?: '-') ?></div>
                            </td>
                            <td class="px-4 py-4 align-top text-sm text-slate-600">
                                <div><span class="font-semibold text-slate-800">Peminjam:</span> <?= e($row['borrower_unit_name'] ?: '-') ?></div>
                                <div class="mt-1"><span class="font-semibold text-slate-800">Pemberi:</span> <?= e($row['lender_unit_name'] ?: '-') ?></div>
                            </td>
                            <td class="px-4 py-4 align-top text-sm text-slate-600">
                                <div><?= e($row['borrower_name']) ?></div>
                                <div class="mt-1 text-xs text-slate-500">Tgl: <?= e(date('d/m/Y', strtotime($row['loan_date']))) ?></div>
                                <div class="mt-1 text-xs <?= $isOverdue ? 'font-bold text-rose-600' : 'text-slate-500' ?>">Rencana kembali: <?= $row['planned_return_date'] ? e(date('d/m/Y', strtotime($row['planned_return_date']))) : '-' ?></div>
                            </td>
                            <td class="px-4 py-4 align-top text-sm text-slate-600">
                                <?php if ($row['status'] === 'dikembalikan'): ?>
                                    <div>Tgl: <?= e(date('d/m/Y', strtotime($row['return_date']))) ?></div>
                                    <div class="mt-1 text-xs">Penerima: <?= e($row['receiver_name'] ?: '-') ?></div>
                                    <div class="mt-1 text-xs">Menyerahkan: <?= e($row['handover_name'] ?: '-') ?></div>
                                    <div class="mt-1 text-xs">Kondisi akhir: <?= e($row['condition_after'] ?: '-') ?></div>
                                <?php else: ?>
                                    <span class="text-slate-400">Belum dikembalikan</span>
                                <?php endif; ?>
                            </td>
                            <td class="px-4 py-4 align-top">
                                <?= pa_status_badge((string)$row['status']) ?>
                                <?php if ($isOverdue): ?>
                                    <div class="mt-2 text-xs font-bold text-rose-600"><i class="fas fa-exclamation-circle mr-1"></i>Lewat rencana</div>
                                <?php endif; ?>
                            </td>
                            <td class="px-4 py-4 align-top text-right">
                                <?php if ($row['status'] === 'dipinjam'): ?>
                                    <button type="button" onclick="openReturnModal(<?= (int)$row['id'] ?>, '<?= e($row['loan_number']) ?>', '<?= e($row['tool_name']) ?>')" class="rounded-xl bg-emerald-600 px-3 py-2 text-xs font-bold text-white hover:bg-emerald-700"><i class="fas fa-undo mr-1"></i>Kembalikan</button>
                                <?php endif; ?>
                                <?php if ($isAdminLike): ?>
                                    <form method="post" class="mt-2 inline-block" onsubmit="return confirm('Hapus data peminjaman ini?')">
                                        <input type="hidden" name="form_action" value="delete_loan">
                                        <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                                        <button class="rounded-xl border border-rose-200 px-3 py-2 text-xs font-bold text-rose-600 hover:bg-rose-50"><i class="fas fa-trash mr-1"></i>Hapus</button>
                                    </form>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php endif; ?>
</div>

<div id="returnModal" class="fixed inset-0 z-50 hidden items-center justify-center bg-slate-900/60 p-4">
    <div class="w-full max-w-2xl rounded-3xl bg-white p-6 shadow-2xl">
        <div class="mb-4 flex items-start justify-between gap-3">
            <div>
                <h3 class="text-xl font-bold text-slate-800">Form Pengembalian Alat</h3>
                <p id="returnModalSubtitle" class="mt-1 text-sm text-slate-500"></p>
            </div>
            <button type="button" onclick="closeReturnModal()" class="rounded-full bg-slate-100 px-3 py-2 text-slate-600 hover:bg-slate-200"><i class="fas fa-times"></i></button>
        </div>
        <form method="post" class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <input type="hidden" name="form_action" value="return_loan">
            <input type="hidden" name="id" id="returnLoanId">
            <div>
                <label class="block text-sm font-semibold text-slate-700 mb-1">Tanggal Pengembalian *</label>
                <input type="date" name="return_date" value="<?= date('Y-m-d') ?>" required class="w-full rounded-xl border border-slate-200 px-4 py-3">
            </div>
            <div>
                <label class="block text-sm font-semibold text-slate-700 mb-1">Kondisi Saat Kembali</label>
                <select name="condition_after" class="w-full rounded-xl border border-slate-200 px-4 py-3">
                    <option value="Baik">Baik</option>
                    <option value="Cukup">Cukup</option>
                    <option value="Rusak Ringan">Rusak Ringan</option>
                    <option value="Rusak / Perlu Perbaikan">Rusak / Perlu Perbaikan</option>
                </select>
            </div>
            <div>
                <label class="block text-sm font-semibold text-slate-700 mb-1">Nama Penerima *</label>
                <input name="receiver_name" required class="w-full rounded-xl border border-slate-200 px-4 py-3" placeholder="Nama staf penerima alat">
            </div>
            <div>
                <label class="block text-sm font-semibold text-slate-700 mb-1">Nama yang Menyerahkan *</label>
                <input name="handover_name" required class="w-full rounded-xl border border-slate-200 px-4 py-3" placeholder="Nama staf yang menyerahkan alat">
            </div>
            <div class="md:col-span-2">
                <label class="block text-sm font-semibold text-slate-700 mb-1">Catatan Pengembalian</label>
                <textarea name="notes" rows="3" class="w-full rounded-xl border border-slate-200 px-4 py-3" placeholder="Catatan tambahan bila ada"></textarea>
            </div>
            <div class="md:col-span-2 flex justify-end gap-2">
                <button type="button" onclick="closeReturnModal()" class="rounded-xl border border-slate-200 px-5 py-3 text-sm font-semibold text-slate-600 hover:bg-slate-50">Batal</button>
                <button class="rounded-xl bg-emerald-600 px-5 py-3 text-sm font-bold text-white hover:bg-emerald-700"><i class="fas fa-save mr-2"></i>Simpan Pengembalian</button>
            </div>
        </form>
    </div>
</div>

<script>
function openReturnModal(id, number, toolName) {
    const modal = document.getElementById('returnModal');
    document.getElementById('returnLoanId').value = id;
    document.getElementById('returnModalSubtitle').textContent = number + ' - ' + toolName;
    modal.classList.remove('hidden');
    modal.classList.add('flex');
}
function closeReturnModal() {
    const modal = document.getElementById('returnModal');
    modal.classList.add('hidden');
    modal.classList.remove('flex');
}
</script>
