<?php

namespace ChurchCRM\Reports;

use ChurchCRM\data\Countries;
use ChurchCRM\dto\SystemConfig;
use ChurchCRM\model\ChurchCRM\FamilyQuery;
use FPDF;

// This class definition contains a bunch of configuration stuff and utilities
// that are useful to all the reports generated by ChurchInfo

// Load the FPDF library

#[\AllowDynamicProperties]
class ChurchInfoReport extends FPDF
{
    // Paper size for all PDF report documents
    // Sizes: A3, A4, A5, Letter, Legal, or a 2-element array for custom size
    // Sorry -- This should really be set in database, but it is needed before all the report settings
    // are read from the database.

    public string $paperFormat = 'Letter';

    /**
     * Converts a UTF-8 string to ISO-8859-1 for FPDF compatibility.
     * Uses iconv() if available, falls back to mb_convert_encoding().
     */
    public static function convertToLatin1(string $str): string
    {
        if (function_exists('iconv')) {
            $result = iconv('UTF-8', 'ISO-8859-1//TRANSLIT//IGNORE', $str);
            if ($result !== false) {
                return $result;
            }
        }
        $result = mb_convert_encoding($str, 'ISO-8859-1', 'UTF-8');
        return is_string($result) ? $result : $str;
    }

    public function printRightJustified($x, $y, $str): void
    {
        $strconv = self::convertToLatin1($str);
        $iLen = strlen($strconv);
        $nMoveBy = 10 - 2 * $iLen;
        $this->SetXY($x + $nMoveBy, $y);
        $this->Write(SystemConfig::getValue('incrementY'), $strconv);
    }

    public function printRightJustifiedCell($x, $y, $wid, $str): void
    {
        $strconv = self::convertToLatin1($str);
        $this->SetXY($x, $y);
        $this->Cell($wid, SystemConfig::getValue('incrementY'), $strconv, 1, 0, 'R');
    }

    public function printCenteredCell($x, $y, $wid, $str): void
    {
        $strconv = self::convertToLatin1($str);
        $this->SetXY($x, $y);
        $this->Cell($wid, SystemConfig::getValue('incrementY'), $strconv, 1, 0, 'C');
    }

    public function writeAt($x, $y, $str): void
    {
        $strconv = self::convertToLatin1($str);
        $this->SetXY($x, $y);
        $this->Write(SystemConfig::getValue('incrementY'), $strconv);
    }

    public function writeAtCell($x, $y, $wid, $str): void
    {
        $strconv = self::convertToLatin1($str);
        $this->SetXY($x, $y);
        $this->MultiCell($wid, 4, $strconv, 1);
    }

    public function startLetterPage($fam_ID, $fam_Name, $fam_Address1, $fam_Address2, string $fam_City, string $fam_State, string $fam_Zip, $fam_Country, $letterhead = ''): float
    {
        $this->addPage();

        if ($letterhead == 'graphic' && is_readable(SystemConfig::getValue('bDirLetterHead'))) {
            $this->Image(SystemConfig::getValue('bDirLetterHead'), 12, 15, 185);
            $curY = 20 + (SystemConfig::getValue('incrementY') * 3) + 25;
            $this->writeAt(170, $curY, date(SystemConfig::getValue('sDateFormatLong')));
        } elseif ($letterhead == 'none') {
            $curY = 20 + (SystemConfig::getValue('incrementY') * 3) + 25;
            $this->writeAt(170, $curY, date(SystemConfig::getValue('sDateFormatLong')));
        } else {
            $dateX = 170;
            $dateY = 25;
            $this->writeAt($dateX, $dateY, date(SystemConfig::getValue('sDateFormatLong')));
            $curY = 20;
            $this->writeAt(SystemConfig::getValue('leftX'), $curY, (string) SystemConfig::getValue('sChurchName'));
            $curY += SystemConfig::getValue('incrementY');
            $this->writeAt(SystemConfig::getValue('leftX'), $curY, (string) SystemConfig::getValue('sChurchAddress'));
            $curY += SystemConfig::getValue('incrementY');
            $this->writeAt(SystemConfig::getValue('leftX'), $curY, (string) SystemConfig::getValue('sChurchCity') . ', ' . (string) SystemConfig::getValue('sChurchState') . '  ' . (string) SystemConfig::getValue('sChurchZip'));
            $curY += SystemConfig::getValue('incrementY');
            $curY += SystemConfig::getValue('incrementY'); // Skip another line before the phone/email
            $this->writeAt(SystemConfig::getValue('leftX'), $curY, (string) SystemConfig::getValue('sChurchPhone') . '  ' . (string) SystemConfig::getValue('sChurchEmail'));
            $curY += 25; // mm to move to the second window
        }
        $this->writeAt(SystemConfig::getValue('leftX'), $curY, $this->makeSalutation($fam_ID));
        $curY += SystemConfig::getValue('incrementY');
        if ($fam_Address1 !== null && $fam_Address1 !== '') {
            $this->writeAt(SystemConfig::getValue('leftX'), $curY, (string) $fam_Address1);
            $curY += SystemConfig::getValue('incrementY');
        }
        if ($fam_Address2 !== null && $fam_Address2 !== '') {
            $this->writeAt(SystemConfig::getValue('leftX'), $curY, (string) $fam_Address2);
            $curY += SystemConfig::getValue('incrementY');
        }
        $this->writeAt(SystemConfig::getValue('leftX'), $curY, $fam_City . ', ' . $fam_State . '  ' . $fam_Zip);
        $curY += SystemConfig::getValue('incrementY');
        if (Countries::isForeign($fam_Country)) {
            $this->writeAt(SystemConfig::getValue('leftX'), $curY, (string) $fam_Country);
            $curY += SystemConfig::getValue('incrementY');
        } // mm to get away from the second window

        return $curY + 5.0;
    }

    public function makeSalutation($famID): string
    {
        $family = FamilyQuery::create()->findPk($famID);

        if ($family === null) {
            return gettext('Dear Friend');  // Default salutation for unassigned/orphaned payments
        }

        return $family->getSalutation();
    }
}
