<?php
require_once dirname(__DIR__) . '/vendor/autoload.php';
use SLiMS\DB;
use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;


if (!function_exists('getBaseDir')) {
    function getBaseDir(string $additionalPath = '') {
        return dirname(__DIR__) . '/' . str_replace('..', '', $additionalPath);
    }
}

if (!function_exists('bpGetLibraryId')) {
    function bpGetLibraryId() {
        if (isset($_SESSION['user_library_id'])) return (int)$_SESSION['user_library_id'];
        if (isset($_SESSION['library_id'])) return (int)$_SESSION['library_id'];
        return 1;
    }
}

if (!function_exists('isSuperadmin')) {
    function isSuperadmin() {
        return (isset($_SESSION['uid']) && $_SESSION['uid'] == 1);
    }
}

if (!function_exists('getSetting')) {
    function getSetting($library_id = null) {
        $db = DB::getInstance();
        
        $state = $db->prepare('SELECT * FROM bebas_pustaka_settings WHERE library_id IS NULL');
        $state->execute();
        $global = $state->fetch(PDO::FETCH_ASSOC);
        
        if ($library_id) {
            $state = $db->prepare('SELECT * FROM bebas_pustaka_settings WHERE library_id = ?');
            $state->execute([$library_id]);
            if ($state->rowCount() > 0) {
                $local = $state->fetch(PDO::FETCH_ASSOC);
                return array_merge($global ?: [], $local);
            }
            if ($global) return $global;
        }
        
        if ($global) return $global;
        
        return [
            'letter_format' => '{code}/BEBAS/{no}/{y}',
            'open_state_default' => 'Yang bertanda tangan di bawah ini, Kepala Perpustakaan, menerangkan bahwa:',
            'close_state_default' => 'Demikian surat ini dibuat untuk digunakan sebagaimana mestinya.',
            'city' => 'Purwokerto',
            'librarian_position' => 'Kepala Perpustakaan'
        ];
    }
}

if (!function_exists('getLibraryData')) {
    function getLibraryData($id) {
        $db = DB::getInstance();
        $state = $db->prepare('SELECT * FROM mst_library WHERE library_id = ?');
        $state->execute([$id]);
        return $state->fetch(PDO::FETCH_ASSOC);
    }
}

if (!function_exists('getLibraryBySlug')) {
    function getLibraryBySlug($slug) {
        $db = DB::getInstance();
        $st = $db->prepare("SELECT * FROM mst_library WHERE library_code = ?");
        $st->execute([$slug]);
        return $st->fetch(PDO::FETCH_ASSOC);
    }
}

if (!function_exists('generateSuratNo')) {
    function generateSuratNo($format, $code, $libId) {
        $db = DB::getInstance();
        $year = date('Y');
        $state = $db->prepare('SELECT COUNT(*) FROM bebas_pustaka_history WHERE library_id = ? AND YEAR(created_at) = ? AND status = "done"');
        $state->execute([$libId, $year]);
        $no = str_pad($state->fetchColumn() + 1, 3, '0', STR_PAD_LEFT);
        return str_replace(['{code}','{no}','{y}','{m}','{d}'], [$code, $no, $year, date('m'), date('d')], $format);
    }
}

// ============================================================
// FUNGSI: CEK PINJAMAN MEMBER
// ============================================================
if (!function_exists('getPinjamanAktifMember')) {
    function getPinjamanAktifMember($member_id, $library_id) {
        $db = DB::getInstance();
        
        $st = $db->prepare("
            SELECT l.item_code, b.title, l.due_date, l.loan_date
            FROM loan l 
            LEFT JOIN item i ON l.item_code = i.item_code 
            LEFT JOIN biblio b ON i.biblio_id = b.biblio_id 
            WHERE l.member_id = ? 
            AND l.is_lent = 1 
            AND l.is_return = 0 
            AND l.library_id = ?
            ORDER BY l.due_date ASC
        ");
        $st->execute([$member_id, $library_id]);
        return $st->fetchAll(PDO::FETCH_ASSOC);
    }
}

// ============================================================
// FUNGSI: CEK DENDA MEMBER
// ============================================================
if (!function_exists('getDendaMember')) {
    function getDendaMember($member_id, $library_id) {
        $db = DB::getInstance();
        
        $st = $db->prepare("
            SELECT 
                fines_id,
                fines_date,
                description,
                debet,
                credit,
                status
            FROM fines
            WHERE member_id = ? 
            AND library_id = ?
            AND status IN ('unpaid', 'partial')
            ORDER BY fines_date DESC
        ");
        $st->execute([$member_id, $library_id]);
        $denda = $st->fetchAll(PDO::FETCH_ASSOC);
        
        $total = 0;
        foreach ($denda as &$d) {
            $d['remaining'] = $d['debet'] - $d['credit'];
            $total += $d['remaining'];
        }
        
        return [
            'detail' => $denda,
            'total' => $total
        ];
    }
}

// ============================================================
// FUNGSI: CEK SYARAT (PINJAMAN + DENDA)
// ============================================================
if (!function_exists('cekSyaratBebasPustaka')) {
    function cekSyaratBebasPustaka($member_id, $library_id) {
        $pinjam = getPinjamanAktifMember($member_id, $library_id);
        $denda = getDendaMember($member_id, $library_id);
        
        $ok = (empty($pinjam) && $denda['total'] == 0);
        
        return [
            'ok' => $ok,
            'pinjam' => $pinjam,
            'denda_detail' => $denda['detail'],
            'denda_total' => $denda['total'],
            'message' => $ok ? '✅ Tidak ada pinjaman aktif dan denda.' : '❌ Masih ada pinjaman aktif atau denda.'
        ];
    }
}

// ============================================================
// FUNGSI: ALLOWED LIBRARIES
// ============================================================
if (!function_exists('getAllowedLibraries')) {
    function getAllowedLibraries($member_id) {
        $db = DB::getInstance();
        $libs = [];
        
        try {
            $st = $db->prepare("
                SELECT DISTINCT library_id 
                FROM member_member_type 
                WHERE member_id = ? AND is_active = 1
            ");
            $st->execute([$member_id]);
            $result = $st->fetchAll(PDO::FETCH_COLUMN);
            
            if (!empty($result)) {
                $libs = $result;
            }
        } catch (PDOException $e) {
            error_log("member_member_type table not found: " . $e->getMessage());
        }
        
        // Fallback: dari session
        if (empty($libs) && isset($_SESSION['library_id'])) {
            $libs[] = (int)$_SESSION['library_id'];
        }
        
        // Fallback: dari URL
        if (empty($libs) && isset($_GET['lib'])) {
            $slug = $_GET['lib'];
            try {
                $st = $db->prepare("SELECT library_id FROM mst_library WHERE library_code = ?");
                $st->execute([$slug]);
                $lib = $st->fetch(PDO::FETCH_ASSOC);
                if ($lib) {
                    $libs[] = (int)$lib['library_id'];
                }
            } catch (PDOException $e) {}
        }
        
        
        return array_unique($libs);
    }
}

// ============================================================
// FUNGSI: CEK DUPLIKAT PENGAJUAN
// ============================================================
if (!function_exists('cekDuplikatPengajuan')) {
    function cekDuplikatPengajuan($member_id, $library_id) {
        $db = DB::getInstance();
        $st = $db->prepare("
            SELECT COUNT(*) 
            FROM bebas_pustaka_history 
            WHERE member_id = ? 
            AND library_id = ? 
            AND status IN ('pending', 'revision')
        ");
        $st->execute([$member_id, $library_id]);
        return $st->fetchColumn() > 0;
    }
}

// ============================================================
// FUNGSI: SUBMIT PENGAJUAN
// ============================================================
if (!function_exists('submitPengajuan')) {
    function submitPengajuan($member_id, $keperluan, $library_id, $keterangan = '') {
        $db = DB::getInstance();
        
        // Cek duplikat
        if (cekDuplikatPengajuan($member_id, $library_id)) {
            return ['ok' => false, 'message' => 'Anda masih memiliki pengajuan aktif untuk perpustakaan ini.'];
        }
        
        // Cek syarat
        $syarat = cekSyaratBebasPustaka($member_id, $library_id);
        if (!$syarat['ok']) {
            return ['ok' => false, 'message' => 'Masih ada pinjaman aktif atau denda.', 'syarat' => $syarat];
        }
        
        // Simpan
        $st = $db->prepare("
            INSERT INTO bebas_pustaka_history 
            (member_id, library_id, keperluan, keterangan, status, uid, created_at, updated_at) 
            VALUES (?, ?, ?, ?, 'pending', ?, NOW(), NOW())
        ");
        $st->execute([$member_id, $library_id, $keperluan, $keterangan, $_SESSION['uid'] ?? 0]);
        
        $id = $db->lastInsertId();
        
        return ['ok' => true, 'id' => $id, 'status' => 'pending'];
    }
}

// ============================================================
// FUNGSI: AMBIL RIWAYAT PENGAJUAN MEMBER
// ============================================================
if (!function_exists('getPengajuanMember')) {
    function getPengajuanMember($member_id) {
        $db = DB::getInstance();
        $st = $db->prepare("
            SELECT h.*, l.library_name
            FROM bebas_pustaka_history h
            LEFT JOIN mst_library l ON h.library_id = l.library_id
            WHERE h.member_id = ?
              AND h.status IN ('pending', 'revision', 'done')
            ORDER BY h.created_at DESC
        ");
        $st->execute([$member_id]);
        return $st->fetchAll(PDO::FETCH_ASSOC);
    }
}

// ============================================================
// FUNGSI: UPDATE STATUS PENGAJUAN (ADMIN)
// ============================================================
if (!function_exists('updateStatusPengajuan')) {
    function updateStatusPengajuan($id, $status, $reason = '', $uid = null) {
        $db = DB::getInstance();
        $uid = $uid ?? $_SESSION['uid'] ?? 0;
        
        if ($status == 'revision') {
            $st = $db->prepare("
                UPDATE bebas_pustaka_history 
                SET status = ?, rejected_reason = ?, updated_at = NOW() 
                WHERE id = ?
            ");
            return $st->execute([$status, $reason, $id]);
        } elseif ($status == 'done') {
            // Generate surat dan PDF
            $st = $db->prepare("SELECT * FROM bebas_pustaka_history WHERE id = ?");
            $st->execute([$id]);
            $history = $st->fetch(PDO::FETCH_ASSOC);
            
            if (!$history) return false;
            
            // Generate nomor surat jika belum ada
            if (empty($history['surat_no'])) {
                $libData = getLibraryData($history['library_id']);
                $setting = getSetting($history['library_id']);
                $code = $libData['library_code'] ?? 'PUSAT';
                $surat_no = generateSuratNo($setting['letter_format'], $code, $history['library_id']);
                
                $st = $db->prepare("
                    UPDATE bebas_pustaka_history 
                    SET surat_no = ?, approved_by = ?, approved_at = NOW() 
                    WHERE id = ?
                ");
                $st->execute([$surat_no, $uid, $id]);
            }
            
            // Generate PDF
            $st = $db->prepare("
                SELECT h.*, m.member_name, l.library_name
                FROM bebas_pustaka_history h
                LEFT JOIN member m ON h.member_id = m.member_id
                LEFT JOIN mst_library l ON h.library_id = l.library_id
                WHERE h.id = ?
            ");
            $st->execute([$id]);
            $history = $st->fetch(PDO::FETCH_ASSOC);
            
            if (!$history) return false;
            
            $libData = getLibraryData($history['library_id']);
            $setting = getSetting($history['library_id']);
            
            $data = [
                'library_id' => $history['library_id'],
                'member_id' => $history['member_id'],
                'member_name' => $history['member_name'],
                'surat_no' => $history['surat_no'],
                'keperluan' => $history['keperluan'],
                'tanggal' => date('d F Y'),
                'library_name' => $libData['library_name'] ?? '',
                'city' => $setting['city'] ?? 'Purwokerto',
                'librarian_position' => $setting['librarian_position'] ?? 'Kepala Perpustakaan',
                'head_name' => $libData['head_name'] ?? '',
                'head_nip' => $libData['head_nip'] ? 'NIP. ' . $libData['head_nip'] : '',
                'keterangan' => $history['keterangan'] ?? ''
            ];
            
            $htmlContent = generateCertificate($data);
            $layout = getTemplate('layout.html');
            if ($layout) $htmlContent = str_replace('{content}', $htmlContent, $layout);
            
            $member_id = $history['member_id'];
            $surat_no = str_replace('/', '_', $history['surat_no']);
            $pdfFilename = $member_id . '_' . $surat_no . '_' . date('Y-m-d') . '.pdf';
            $pdfPath = savePdfToFile($htmlContent, $pdfFilename);
            
            // Update status dan file_path
            $st = $db->prepare("
                UPDATE bebas_pustaka_history 
                SET status = 'done', 
                    file_path = ?, 
                    approved_by = ?, 
                    approved_at = NOW(), 
                    updated_at = NOW() 
                WHERE id = ?
            ");
            return $st->execute([$pdfPath, $uid, $id]);
        }
        
        return false;
    }
}

// ============================================================
// FUNGSI: CETAK ULANG PDF (UNTUK MEMBER DOWNLOAD)
// ============================================================
if (!function_exists('getPdfPath')) {
    function getPdfPath($id, $member_id) {
        $db = DB::getInstance();
        $st = $db->prepare("
            SELECT file_path FROM bebas_pustaka_history 
            WHERE id = ? AND member_id = ? AND status = 'done'
        ");
        $st->execute([$id, $member_id]);
        $result = $st->fetch(PDO::FETCH_ASSOC);
        return $result ? $result['file_path'] : null;
    }
}

// ============================================================
// FUNGSI: GET KEPERLUAN LIST
// ============================================================
if (!function_exists('getKeperluanList')) {
    function getKeperluanList($library_id = null) {
        $db = DB::getInstance();
        $sql = "
            SELECT keperluan, open_state, close_state 
            FROM bebas_pustaka_keperluan 
            WHERE is_active = 1 
            AND (library_id = ? OR library_id IS NULL)
            ORDER BY sort_order ASC, keperluan ASC
        ";
        $st = $db->prepare($sql);
        $st->execute([$library_id]);
        return $st->fetchAll(PDO::FETCH_ASSOC);
    }
}

// ============================================================
// FUNGSI: GET REDAKSI
// ============================================================
if (!function_exists('getRedaksi')) {
    function getRedaksi($library_id, $keperluan) {
        $db = DB::getInstance();
        
        $st = $db->prepare("
            SELECT open_state, close_state 
            FROM bebas_pustaka_keperluan 
            WHERE library_id = ? AND keperluan = ? AND is_active = 1
        ");
        $st->execute([$library_id, $keperluan]);
        $result = $st->fetch(PDO::FETCH_ASSOC);
        
        if ($result) return $result;
        
        $st = $db->prepare("
            SELECT open_state, close_state 
            FROM bebas_pustaka_keperluan 
            WHERE library_id IS NULL AND keperluan = ? AND is_active = 1
        ");
        $st->execute([$keperluan]);
        $result = $st->fetch(PDO::FETCH_ASSOC);
        
        if ($result) return $result;
        
        $setting = getSetting($library_id);
        return [
            'open_state' => $setting['open_state_default'] ?? 'Yang bertanda tangan di bawah ini, Kepala Perpustakaan, menerangkan bahwa:',
            'close_state' => $setting['close_state_default'] ?? 'Demikian surat ini dibuat untuk digunakan sebagaimana mestinya.'
        ];
    }
}

// ============================================================
// FUNGSI: QR CODE
// ============================================================
if (!function_exists('generateQRCode')) {
    function generateQRCode($data) {
        $options = new QROptions([
            'outputType' => QRCode::OUTPUT_IMAGE_PNG,
            'eccLevel'   => QRCode::ECC_M,
            'scale'      => 5,
        ]);
        $pngData = (new QRCode($options))->render($data);
        if (strpos($pngData, 'data:image') !== 0) {
            $pngData = 'data:image/png;base64,'.base64_encode($pngData);
        }
        return $pngData;
    }
}

// ============================================================
// FUNGSI: GENERATE CERTIFICATE
// ============================================================
if (!function_exists('generateCertificate')) {
    function generateCertificate($data) {
        $redaksi = getRedaksi($data['library_id'] ?? 0, $data['keperluan'] ?? '');
        
        $qrData = 'Nama:' . ($data['member_name'] ?? '') . 
                  '|ID:' . ($data['member_id'] ?? '') . 
                  '|Tgl:' . ($data['tanggal'] ?? '') . 
                  '|Surat:' . ($data['surat_no'] ?? '') . 
                  '|Perpus:' . ($data['library_name'] ?? '');
        
        $libId = $data['library_id'] ?? 0;
        
        $logoPath = dirname(__DIR__) . '/static/' . $libId . '/logo.png';
        if (!file_exists($logoPath)) $logoPath = dirname(__DIR__) . '/static/global/logo.png';
        if (!file_exists($logoPath)) $logoPath = dirname(__DIR__) . '/static/logo.png';
        $logo = file_exists($logoPath) ? 'data:image/png;base64,' . base64_encode(file_get_contents($logoPath)) : '';
        
        $ttdPath = dirname(__DIR__) . '/static/' . $libId . '/signature.png';
        if (!file_exists($ttdPath)) $ttdPath = dirname(__DIR__) . '/static/global/signature.png';
        if (!file_exists($ttdPath)) $ttdPath = dirname(__DIR__) . '/static/signature.png';
        $ttd = file_exists($ttdPath) ? 'data:image/png;base64,' . base64_encode(file_get_contents($ttdPath)) : '';
        
        $stempelPath = dirname(__DIR__) . '/static/' . $libId . '/stempel.png';
        if (!file_exists($stempelPath)) $stempelPath = dirname(__DIR__) . '/static/global/stempel.png';
        if (!file_exists($stempelPath)) $stempelPath = dirname(__DIR__) . '/static/stempel.png';
        $stempel = file_exists($stempelPath) ? 'data:image/png;base64,' . base64_encode(file_get_contents($stempelPath)) : '';
        
        $templateData = array_merge($data, [
            'logo' => $logo,
            'ttd' => $ttd,
            'stempel' => $stempel,
            'qr_code' => generateQRCode($qrData),
            'open_state' => $redaksi['open_state'] ?? $data['open_state'] ?? 'Yang bertanda tangan di bawah ini, Kepala Perpustakaan, menerangkan bahwa:',
            'close_state' => $redaksi['close_state'] ?? $data['close_state'] ?? 'Demikian surat ini dibuat untuk digunakan sebagaimana mestinya.',
            'phone' => $data['phone'] ?? '',
            'email' => $data['email'] ?? '',
            'institusi' => $data['institusi'] ?? 'Universitas Jenderal Soedirman',
            'keterangan' => !empty($data['keterangan']) ? ' (' . $data['keterangan'] . ')' : ''
        ]);
        
        return parseTemplate(getTemplate('certificate.html'), $templateData);
    }
}

// ============================================================
// FUNGSI: SAVE PDF TO FILE
// ============================================================
if (!function_exists('savePdfToFile')) {
    function savePdfToFile($htmlContent, $filename) {
        $pdfDir = dirname(__DIR__) . '/file_bebas_pustaka/';
        if (!is_dir($pdfDir)) {
            mkdir($pdfDir, 0755, true);
        }
        $pdfPath = $pdfDir . $filename;
        $dompdf = new \Dompdf\Dompdf();
        $dompdf->loadHtml($htmlContent);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();
        $pdfContent = $dompdf->output();
        file_put_contents($pdfPath, $pdfContent);
        return $pdfPath;
    }
}

// ============================================================
// FUNGSI: TEMPLATE
// ============================================================
if (!function_exists('getTemplate')) {
    function getTemplate($filename) {
        $path = dirname(__DIR__) . '/template/' . $filename;
        return file_exists($path) ? file_get_contents($path) : '';
    }
}

if (!function_exists('parseTemplate')) {
    function parseTemplate($template, array $data) {
        foreach ($data as $key => $value) {
            $template = str_replace('{' . $key . '}', $value ?? '', $template);
        }
        return $template;
    }
}

// ============================================================
// FUNGSI: GET PENGAJUAN ALL (UNTUK ADMIN)
// ============================================================
if (!function_exists('getAllPengajuan')) {
    function getAllPengajuan($library_id = null, $status = null) {
        $db = DB::getInstance();
        $sql = "
            SELECT h.*, m.member_name, l.library_name
            FROM bebas_pustaka_history h
            LEFT JOIN member m ON h.member_id = m.member_id
            LEFT JOIN mst_library l ON h.library_id = l.library_id
            WHERE 1=1
        ";
        $params = [];
        
        if ($library_id) {
            $sql .= " AND h.library_id = ?";
            $params[] = $library_id;
        }
        if ($status) {
            $sql .= " AND h.status = ?";
            $params[] = $status;
        }
        
        $sql .= " ORDER BY h.created_at DESC";
        
        $st = $db->prepare($sql);
        $st->execute($params);
        return $st->fetchAll(PDO::FETCH_ASSOC);
    }
}
?>