<?php
/**
 * Upload Berkas (File Upload)
 * Koperasi Management System
 */

$pageTitle = 'Upload Berkas';
$pageSubtitle = 'Kelola berkas dokumen pinjaman anggota';

require_once __DIR__ . '/../config/database.php';
$db = getDB();

// Handle Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'upload') {
        $anggotaId = $_POST['anggota_id'] ?? '';
        $pinjamanId = $_POST['pinjaman_id'] ?? '';
        $keterangan = sanitize($_POST['keterangan'] ?? '');

        if (empty($anggotaId) || empty($pinjamanId) || empty($_FILES['berkas']['name'])) {
            setFlash('danger', 'Gagal: Semua field harus diisi.');
            header('Location: upload_berkas.php');
            exit;
        }

        $file = $_FILES['berkas'];
        $fileName = $file['name'];
        $fileTmp = $file['tmp_name'];
        $fileSize = $file['size'];
        $fileError = $file['error'];
        $fileType = $file['type'];

        $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        $newFileName = uniqid('BRK_', true) . '.' . $fileExt;
        $uploadDir = 'uploads/berkas_pinjaman/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        $destPath = $uploadDir . $newFileName;

        if ($fileError === 0) {
            if (move_uploaded_file($fileTmp, $destPath)) {
                $stmt = $db->prepare("INSERT INTO berkas_pinjaman (anggota_id, pinjaman_id, nama_berkas, file_path, file_type, file_size, keterangan, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([
                    $anggotaId,
                    $pinjamanId,
                    $fileName,
                    $newFileName,
                    $fileType,
                    $fileSize,
                    $keterangan,
                    $_SESSION['user_id']
                ]);
                setFlash('success', 'Berkas berhasil diupload.');
            } else {
                $errorMsg = 'Gagal memindahkan file ke direktori tujuan.';
                if (!is_writable($uploadDir)) {
                    $errorMsg .= ' Folder tujuan tidak memiliki izin tulis.';
                }
                setFlash('danger', $errorMsg);
            }
        } else {
            $phpErrors = [
                1 => 'Ukuran file melampaui batas upload_max_filesize di php.ini.',
                2 => 'Ukuran file melampaui batas MAX_FILE_SIZE di form HTML.',
                3 => 'File hanya terupload sebagian.',
                4 => 'Tidak ada file yang diupload.',
                6 => 'Folder sementara (tmp) hilang.',
                7 => 'Gagal menulis file ke disk.',
                8 => 'Ekstensi PHP menghentikan proses upload.'
            ];
            $msg = $phpErrors[$fileError] ?? 'Terjadi kesalahan saat upload file (Error: ' . $fileError . ').';
            setFlash('danger', $msg);
        }

        header('Location: upload_berkas.php');
        exit;
    }

    if ($action === 'delete') {
        $id = $_POST['id'];
        $stmt = $db->prepare("SELECT file_path FROM berkas_pinjaman WHERE id = ?");
        $stmt->execute([$id]);
        $berkas = $stmt->fetch();

        if ($berkas) {
            $filePath = 'uploads/berkas_pinjaman/' . $berkas['file_path'];
            if (file_exists($filePath)) {
                unlink($filePath);
            }
            $delStmt = $db->prepare("DELETE FROM berkas_pinjaman WHERE id = ?");
            $delStmt->execute([$id]);
            setFlash('success', 'Berkas berhasil dihapus.');
        } else {
            setFlash('danger', 'Berkas tidak ditemukan.');
        }
        header('Location: upload_berkas.php');
        exit;
    }
}

// Handle AJAX for loans
if (isset($_GET['ajax_member_loans'])) {
    header('Content-Type: application/json');
    $aid = intval($_GET['ajax_member_loans']);
    $stmt = $db->prepare("SELECT id, no_pinjaman, jumlah_pinjaman, tanggal_pinjaman FROM pinjaman WHERE anggota_id = ? ORDER BY tanggal_pinjaman DESC");
    $stmt->execute([$aid]);
    $loans = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Count loans for "pinjaman ke"
    $count = count($loans);
    foreach ($loans as $index => &$loan) {
        $loan['pinjaman_ke'] = $count - $index;
        $loan['jumlah_formatted'] = formatRupiah($loan['jumlah_pinjaman']);
    }
    
    echo json_encode($loans);
    exit;
}

// Search and Pagination
$search = $_GET['search'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 10;
$offset = ($page - 1) * $perPage;

$where = "WHERE 1=1";
$params = [];

if ($search) {
    $where .= " AND (a.nama LIKE ? OR b.nama_berkas LIKE ? OR p.no_pinjaman LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$countStmt = $db->prepare("SELECT COUNT(*) FROM berkas_pinjaman b JOIN anggota a ON b.anggota_id = a.id JOIN pinjaman p ON b.pinjaman_id = p.id $where");
$countStmt->execute($params);
$totalRows = $countStmt->fetchColumn();
$totalPages = ceil($totalRows / $perPage);

$stmt = $db->prepare("
    SELECT b.*, a.nama as nama_anggota, p.no_pinjaman, p.jumlah_pinjaman, p.tanggal_pinjaman,
           (SELECT COUNT(*) FROM pinjaman p2 WHERE p2.anggota_id = b.anggota_id AND p2.tanggal_pinjaman <= p.tanggal_pinjaman) as pinjaman_ke
    FROM berkas_pinjaman b
    JOIN anggota a ON b.anggota_id = a.id
    JOIN pinjaman p ON b.pinjaman_id = p.id
    $where
    ORDER BY b.created_at DESC
    LIMIT $perPage OFFSET $offset
");
$stmt->execute($params);
$berkasList = $stmt->fetchAll();

$anggotaList = $db->query("SELECT id, no_anggota, nama FROM anggota WHERE status='aktif' ORDER BY nama")->fetchAll();

include __DIR__ . '/header.php';
?>

<div class="card">
    <div class="card-header">
        <div class="toolbar" style="width: 100%;">
            <div class="search-box">
                <i class="fas fa-search"></i>
                <input type="text" placeholder="Cari berkas, anggota..." value="<?= htmlspecialchars($search) ?>"
                       onkeydown="if(event.key==='Enter') { window.location='upload_berkas.php?search='+this.value; }">
            </div>
            <div style="margin-left: auto;">
                <button class="btn btn-primary" onclick="openModal('uploadModal')">
                    <i class="fas fa-plus"></i> Upload Berkas Baru
                </button>
            </div>
        </div>
    </div>

    <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th style="width: 50px; text-align: center;">No</th>
                    <th>Nama Anggota</th>
                    <th>Info Pinjaman</th>
                    <th>Nama Berkas</th>
                    <th>Ukuran / Tipe</th>
                    <th>Tanggal Upload</th>
                    <th style="width: 120px; text-align: center;">Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($berkasList)): ?>
                    <tr>
                        <td colspan="7" class="text-center text-muted" style="padding: 40px;">
                            <i class="fas fa-file-upload" style="font-size: 2rem; display: block; margin-bottom: 10px; color: var(--gray-300);"></i>
                            Belum ada berkas yang diupload
                        </td>
                    </tr>
                <?php else: ?>
                    <?php $nomor = $offset + 1; foreach ($berkasList as $b): ?>
                        <tr>
                            <td style="text-align: center; font-weight: bold;"><?= $nomor++ ?></td>
                            <td>
                                <div class="fw-bold"><?= htmlspecialchars($b['nama_anggota']) ?></div>
                                <div style="color: var(--gray-500); font-size: 0.8rem;">Pinjaman ke-<?= $b['pinjaman_ke'] ?></div>
                            </td>
                            <td>
                                <div style="font-weight: 700; color: var(--primary-600); font-size: 0.85rem;">#<?= htmlspecialchars($b['no_pinjaman']) ?></div>
                                <div style="font-size: 0.85rem; font-weight: 600;"><?= formatRupiah($b['jumlah_pinjaman']) ?></div>
                            </td>
                            <td>
                                <div class="fw-bold"><?= htmlspecialchars($b['nama_berkas']) ?></div>
                                <?php if ($b['keterangan']): ?>
                                    <div style="color: var(--gray-500); font-size: 0.8rem; font-style: italic;"><?= htmlspecialchars($b['keterangan']) ?></div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div style="font-size: 0.85rem;"><?= round($b['file_size'] / 1024, 2) ?> KB</div>
                                <div style="color: var(--gray-400); font-size: 0.75rem;"><?= htmlspecialchars($b['file_type']) ?></div>
                            </td>
                            <td>
                                <div style="font-size: 0.85rem;"><?= formatTanggal($b['created_at']) ?></div>
                                <div style="color: var(--gray-400); font-size: 0.75rem;"><?= date('H:i', strtotime($b['created_at'])) ?> WIB</div>
                            </td>
                            <td style="text-align: center;">
                                <div class="btn-group">
                                    <a href="<?= APP_URL ?>/view_berkas.php?id=<?= $b['id'] ?>" class="btn btn-sm btn-outline-info" title="Lihat Berkas">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <a href="<?= APP_URL ?>/uploads/berkas_pinjaman/<?= $b['file_path'] ?>" download="<?= htmlspecialchars($b['nama_berkas']) ?>" class="btn btn-sm btn-outline-success" title="Download Berkas">
                                        <i class="fas fa-download"></i>
                                    </a>
                                    <form method="POST" style="display:inline;" onsubmit="return confirm('Hapus berkas ini?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= $b['id'] ?>">
                                        <button type="submit" class="btn btn-sm btn-outline-danger" title="Hapus">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    <?php if ($totalPages > 1): ?>
        <div class="pagination">
            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <a href="<?= APP_URL ?>/includes/upload_berkas.php?page=<?= $i ?>&search=<?= urlencode($search) ?>" class="page-link <?= $i == $page ? 'active' : '' ?>"><?= $i ?></a>
            <?php endfor; ?>
        </div>
    <?php endif; ?>
</div>

<style>
/* Searchable Dropdown & Upload Box Refinements */
.btn-group {
    display: flex;
    gap: 6px;
    justify-content: center;
    align-items: center;
}
.searchable-dropdown {
    position: relative;
    width: 100%;
}
.searchable-dropdown .dropdown-results {
    position: absolute;
    top: calc(100% + 5px);
    left: 0;
    right: 0;
    z-index: 9999;
    background: #ffffff;
    border: 1px solid var(--gray-200);
    border-radius: var(--radius-md);
    box-shadow: 0 10px 25px rgba(0,0,0,0.1);
    max-height: 250px;
    overflow-y: auto;
    display: none;
}
.searchable-dropdown .dropdown-results.active {
    display: block;
}
.searchable-dropdown .dropdown-item {
    padding: 10px 15px;
    cursor: pointer;
    font-size: 0.88rem;
    display: flex;
    align-items: center;
    gap: 10px;
    color: var(--gray-700);
    transition: background 0.2s;
}
.searchable-dropdown .dropdown-item:hover {
    background: var(--primary-50);
}
.searchable-dropdown .dropdown-item i {
    color: var(--gray-400);
}
.searchable-dropdown .dropdown-item.no-results {
    padding: 20px;
    justify-content: center;
    color: var(--danger-500);
}

/* Custom Scrollbar for Dropdown */
.dropdown-results::-webkit-scrollbar {
    width: 6px;
}
.dropdown-results::-webkit-scrollbar-thumb {
    background: var(--gray-300);
    border-radius: 10px;
}

/* Compact Upload Area */
.upload-area {
    border: 2px dashed var(--gray-300);
    padding: 15px;
    text-align: center;
    border-radius: var(--radius-md);
    background: var(--gray-50);
    cursor: pointer;
    transition: all 0.3s;
}
.upload-area:hover {
    border-color: var(--primary-400);
    background: var(--primary-50);
}
</style>

<!-- Upload Modal -->
<div class="modal" id="uploadModal">
    <div class="modal-header">
        <h3><i class="fas fa-file-upload" style="color: var(--primary-500); margin-right: 8px;"></i> Upload Berkas Pinjaman</h3>
        <button class="modal-close" onclick="closeModal('uploadModal')"><i class="fas fa-times"></i></button>
    </div>
    <form method="POST" enctype="multipart/form-data" onsubmit="return validateSearchableDropdown(this)">
        <input type="hidden" name="action" value="upload">
        <div class="modal-body">
            <div class="form-group mb-3">
                <label>Nama Anggota <span class="required">*</span></label>
                <div class="searchable-dropdown">
                    <div class="input-wrapper" style="position: relative;">
                        <i class="fas fa-search" style="position: absolute; left: 14px; top: 50%; transform: translateY(-50%); color: var(--gray-400); pointer-events: none;"></i>
                        <input type="text" id="member_search_input" class="form-control" placeholder="Cari nama anggota..." style="padding-left: 40px;" oninput="filterMemberDropdown(this)" autocomplete="off">
                    </div>
                    <input type="hidden" name="anggota_id" id="member_id_hidden" required>
                    
                    <div class="dropdown-results" id="member_results">
                        <?php foreach ($anggotaList as $agt): ?>
                            <div class="dropdown-item" 
                                 data-id="<?= $agt['id'] ?>" 
                                 data-text="<?= htmlspecialchars($agt['nama']) ?> (<?= $agt['no_anggota'] ?>)">
                                <i class="fas fa-user"></i>
                                <span><?= htmlspecialchars($agt['nama']) ?> (<?= $agt['no_anggota'] ?>)</span>
                            </div>
                        <?php endforeach; ?>
                        <div class="dropdown-item no-results">
                            <i class="fas fa-user-slash"></i>
                            <span>Anggota tidak ditemukan</span>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="form-group mb-3">
                <label>Pilih Pinjaman <span class="required">*</span></label>
                <select name="pinjaman_id" id="pinjaman_select" class="form-control" required disabled>
                    <option value="">-- Pilih Anggota Terlebih Dahulu --</option>
                </select>
                <div id="pinjaman_info" style="margin-top: 5px; font-size: 0.8rem; color: var(--primary-600); font-weight: 600;"></div>
            </div>

            <div class="form-group mb-3">
                <label>File Berkas <span class="required">*</span></label>
                <div class="upload-area" onclick="document.getElementById('file_input').click()">
                    <i class="fas fa-cloud-upload-alt" style="font-size: 1.5rem; color: var(--primary-400); margin-bottom: 5px;"></i>
                    <p style="margin: 0; font-size: 0.85rem; color: var(--gray-600);">Klik atau seret berkas ke sini</p>
                    <p id="file_name_display" style="margin-top: 5px; font-weight: 700; color: var(--success-600); font-size: 0.85rem; display: none;"></p>
                    <input type="file" name="berkas" id="file_input" style="display: none;" required onchange="updateFileName(this)">
                </div>
                <small class="text-muted" style="font-size: 0.75rem;">Format: PDF, JPG, PNG, DOC, dll.</small>
            </div>

            <div class="form-group mb-0">
                <label>Keterangan</label>
                <textarea name="keterangan" class="form-control" rows="2" placeholder="Catatan opsional..."></textarea>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="closeModal('uploadModal')">Batal</button>
            <button type="submit" class="btn btn-primary"><i class="fas fa-cloud-upload-alt"></i> Upload</button>
        </div>
    </form>
</div>

<script>
// Filter Member logic
function filterMemberDropdown(input) {
    const filter = input.value.toLowerCase().trim();
    const container = input.closest('.searchable-dropdown');
    const dropdown = container.querySelector('.dropdown-results');
    const items = dropdown.querySelectorAll('.dropdown-item:not(.no-results)');
    const noResults = dropdown.querySelector('.no-results');
    const hidden = container.querySelector('input[type="hidden"]');
    
    // Reset hidden ID and clear loans if text changes
    hidden.value = '';
    loadMemberLoans(''); 
    input.style.borderColor = '';
    input.style.backgroundColor = '';

    if (filter.length > 0) {
        dropdown.classList.add('active');
        let hasResults = false;
        
        items.forEach(item => {
            const text = item.getAttribute('data-text').toLowerCase();
            if (text.includes(filter)) {
                item.style.setProperty('display', 'flex', 'important');
                hasResults = true;
            } else {
                item.style.setProperty('display', 'none', 'important');
            }
        });
        
        if (noResults) {
            noResults.style.setProperty('display', hasResults ? 'none' : 'flex', 'important');
        }
    } else {
        dropdown.classList.remove('active');
    }
}

// Global handle click selection
document.addEventListener('mousedown', function(e) {
    const item = e.target.closest('.dropdown-item:not(.no-results)');
    // Check if the click is inside our upload modal's searchable dropdown
    if (item && item.closest('#uploadModal')) {
        const container = item.closest('.searchable-dropdown');
        const input = container.querySelector('input[type="text"]');
        const hidden = container.querySelector('input[type="hidden"]');
        const memberId = item.getAttribute('data-id');
        
        input.value = item.getAttribute('data-text').trim();
        hidden.value = memberId;
        
        input.style.setProperty('border-color', 'var(--success-500)', 'important');
        input.style.setProperty('background-color', 'var(--success-50)', 'important');
        
        container.querySelector('.dropdown-results').classList.remove('active');
        
        // Trigger loan loading
        loadMemberLoans(memberId);
        
        e.preventDefault();
        return;
    }

    // Close dropdowns if clicking elsewhere
    if (!e.target.closest('.searchable-dropdown')) {
        document.querySelectorAll('.dropdown-results.active').forEach(d => d.classList.remove('active'));
    }
});

function validateSearchableDropdown(form) {
    const hiddenId = form.querySelector('#member_id_hidden');
    if (!hiddenId || !hiddenId.value) {
        alert('Mohon pilih Nama Anggota dari daftar yang tersedia.');
        form.querySelector('#member_search_input').focus();
        return false;
    }
    return true;
}

function loadMemberLoans(memberId) {
    const loanSelect = document.getElementById('pinjaman_select');
    const infoDiv = document.getElementById('pinjaman_info');
    
    if (!memberId) {
        loanSelect.innerHTML = '<option value="">-- Pilih Anggota Terlebih Dahulu --</option>';
        loanSelect.disabled = true;
        infoDiv.innerHTML = '';
        return;
    }

    loanSelect.innerHTML = '<option value="">Memuat data pinjaman...</option>';
    loanSelect.disabled = true;

    fetch(`upload_berkas.php?ajax_member_loans=${memberId}`)
        .then(response => response.json())
        .then(data => {
            loanSelect.innerHTML = '<option value="">-- Pilih Pinjaman --</option>';
            if (data.length === 0) {
                loanSelect.innerHTML = '<option value="">Tidak ada data pinjaman</option>';
                loanSelect.disabled = true;
                infoDiv.innerHTML = '<span class="text-danger">Anggota ini belum memiliki data pinjaman.</span>';
            } else {
                data.forEach(loan => {
                    const opt = document.createElement('option');
                    opt.value = loan.id;
                    opt.textContent = `Pinjaman ke-${loan.pinjaman_ke} (#${loan.no_pinjaman}) - ${loan.jumlah_formatted}`;
                    opt.dataset.jumlah = loan.jumlah_formatted;
                    opt.dataset.ke = loan.pinjaman_ke;
                    loanSelect.appendChild(opt);
                });
                loanSelect.disabled = false;
                infoDiv.innerHTML = '';
            }
        })
        .catch(err => {
            console.error('Error:', err);
            loanSelect.innerHTML = '<option value="">Gagal memuat data</option>';
        });
}

document.getElementById('pinjaman_select').addEventListener('change', function() {
    const selected = this.options[this.selectedIndex];
    const infoDiv = document.getElementById('pinjaman_info');
    if (this.value) {
        infoDiv.innerHTML = `Terpilih: Pinjaman ke-${selected.dataset.ke} senilai ${selected.dataset.jumlah}`;
    } else {
        infoDiv.innerHTML = '';
    }
});

function updateFileName(input) {
    const display = document.getElementById('file_name_display');
    if (input.files && input.files[0]) {
        display.textContent = "Terpilih: " + input.files[0].name;
        display.style.display = 'block';
    } else {
        display.style.display = 'none';
    }
}
</script>

<?php include __DIR__ . '/footer.php'; ?>
