<?php
/**
 * Premium EMI Schedule PDF Generator - DomPDF
 * Uses base64 encoded images for reliability across all platforms
 */
require_once __DIR__ . '/../../vendor/autoload.php';

use Dompdf\Dompdf;
use Dompdf\Options;

class SchedulePdfService {

    public static function generate(array $loan, array $customer, array $emis): void {
        $settings = self::getCompanySettings();

        // --- Company Logo as base64 ---
        $logoSrc = '';
        $logoSetting = setting('app_logo', '');
        $logoFound = self::findFile([
            $logoSetting ? ('public/' . ltrim($logoSetting, '/')) : null,
            function_exists('app_logo_path') && app_logo_path() ? ('public/' . ltrim(app_logo_path(), '/')) : null,
            'public/uploads/branding/fx_6a19f335aa54d8.28778505.png',
            'public/assets/images/logo.png',
        ]);
        if ($logoFound) {
            $logoSrc = self::base64Img($logoFound);
        }
        $settings['logo_path'] = $logoSrc;

        // --- Customer Photo as base64 ---
        $customerPhoto = '';
        if (!empty($customer['photo'])) {
            $photo = $customer['photo'];
            $photoCandidates = [];
            if (str_starts_with($photo, 'http')) {
                $parsed = parse_url($photo);
                $photoCandidates[] = 'public' . ($parsed['path'] ?? '');
            } else {
                $photoCandidates[] = 'public/' . ltrim(str_replace('\\', '/', $photo), '/');
            }
            $photoCandidates[] = 'public/uploads/photos/fx_6a37a34ec642c7.20400512.png';
            $photoFound = self::findFile($photoCandidates);
            if ($photoFound) {
                $customerPhoto = self::base64Img($photoFound);
            }
        }
        $customer['photo'] = $customerPhoto;

        // --- QR Code (larger, remote URL) ---
        $qrSvg = self::generateQrSvg($loan, $settings);

        // --- Compute totals ---
        $totalInstallment = 0; $totalPrincipal = 0; $totalInterest = 0; $totalPaid = 0;
        foreach ($emis as $e) {
            $totalInstallment += (float)($e['emi_amount'] ?? 0);
            $totalPrincipal   += (float)($e['principal'] ?? 0);
            $totalInterest    += (float)($e['interest'] ?? 0);
            $totalPaid        += (float)($e['paid_amount'] ?? 0);
        }

        // --- Fetch collector names ---
        $emiIds = array_column($emis, 'id');
        $collectorMap = [];
        if (!empty($emiIds)) {
            $cols = db()->query(
                "SELECT c.emi_id, u.name FROM collections c JOIN users u ON c.collected_by = u.id
                 WHERE c.loan_id = ? AND c.emi_id IN (" . implode(',', array_map('intval', $emiIds)) . ")
                 GROUP BY c.emi_id", [(int)$loan['id']]
            );
            foreach ($cols as $c) {
                if (!isset($collectorMap[$c['emi_id']])) $collectorMap[$c['emi_id']] = $c['name'];
            }
        }
        foreach ($emis as &$e) { $e['collector_name'] = $collectorMap[$e['id']] ?? ''; }
        unset($e);

        // --- Render HTML ---
        ob_start();
        $generatedAt = date('d-m-Y h:i A');
        $branchCode = $loan['branch_code'] ?? '';
        require __DIR__ . '/../../views/loans/schedule_pdf.php';
        $html = ob_get_clean();

        // --- DomPDF ---
        $options = new Options();
        $options->set('isRemoteEnabled', true);
        $options->set('isHtml5ParserEnabled', true);
        $options->set('defaultPaperSize', 'A4');
        $options->set('dpi', 150);
        $options->set('isPhpEnabled', false);
        $options->set('isFontSubsettingEnabled', true);
        $options->set('defaultFont', 'dejavu sans');

        $dompdf = new Dompdf($options);
        $dompdf->loadHtml(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        $filename = 'schedule_' . ($loan['loan_no'] ?? 'loan') . '_' . date('Ymd_His') . '.pdf';
        $dompdf->stream($filename, ['Attachment' => true]);
        exit;
    }

    private static function findFile(array $paths): string {
        $root = __DIR__ . '/../../';
        foreach ($paths as $p) {
            if (!$p) continue;
            $abs = realpath($root . ltrim($p, '/'));
            if ($abs && file_exists($abs) && is_file($abs)) {
                return $abs;
            }
        }
        return '';
    }

    private static function base64Img(string $filePath): string {
        $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
        $mime = match($ext) {
            'png' => 'image/png',
            'jpg', 'jpeg' => 'image/jpeg',
            'gif' => 'image/gif',
            'svg' => 'image/svg+xml',
            'webp' => 'image/webp',
            default => 'image/png',
        };
        $data = @file_get_contents($filePath);
        if (!$data) return '';
        return 'data:' . $mime . ';base64,' . base64_encode($data);
    }

    private static function getCompanySettings(): array {
        $keys = [
            'company_name'=>'app_name','address'=>'company_address','phone'=>'company_phone',
            'email'=>'company_email','website'=>'company_website','gst_no'=>'gst_number',
            'cin'=>'cin_number','pan'=>'pan_number','upi_id'=>'payment_upi_id','head_office'=>'head_office',
        ];
        $s = [];
        foreach ($keys as $k => $v) { $s[$k] = setting($v, '') ?: ''; }
        return $s;
    }

    private static function generateQrSvg(array $loan, array $settings): string {
        $upiId = $settings['upi_id'] ?? '';
        if (empty($upiId)) return '';
        $upiUrl = 'upi://pay?pa=' . urlencode($upiId)
                . '&pn=' . urlencode($settings['company_name'] ?? 'BOLT')
                . '&am=' . number_format($loan['outstanding'] ?? 0, 2, '.', '')
                . '&cu=INR';
        $qrApiUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=' . urlencode($upiUrl);
        return '<img src="' . $qrApiUrl . '" alt="QR" width="70" height="70">';
    }
}