<?php

require_once __DIR__ . '/../Include/Config.php';
require_once __DIR__ . '/../Include/PageInit.php';

use ChurchCRM\dto\SystemConfig;
use ChurchCRM\Reports\PdfGroupDirectory;
use ChurchCRM\dto\Cart;
use ChurchCRM\Utils\CustomFieldUtils;
use ChurchCRM\Utils\InputUtils;
use ChurchCRM\Utils\MiscUtils;

$bOnlyCartMembers = $_POST['OnlyCart'];
$iGroupID = InputUtils::legacyFilterInput($_POST['GroupID'], 'int');
$iMode = InputUtils::legacyFilterInput($_POST['ReportModel'], 'int');

if ($iMode == 1) {
    $iRoleID = InputUtils::legacyFilterInput($_POST['GroupRole'], 'int');
} else {
    $iRoleID = 0;
}

// Get the group name
$rsGroupName = RunPreparedQuery('SELECT grp_Name, grp_RoleListID FROM group_grp WHERE grp_ID = ?', 'i', [(int) $iGroupID]);
$aRow = mysqli_fetch_array($rsGroupName);
$sGroupName = $aRow[0];
$iRoleListID = $aRow[1];

// Get the selected role name for the PDF header
if ($iRoleID > 0) {
    $rsTemp = RunPreparedQuery('SELECT lst_OptionName FROM list_lst WHERE lst_ID = ? AND lst_OptionID = ?', 'ii', [(int) $iRoleListID, (int) $iRoleID]);
    $aRow = mysqli_fetch_array($rsTemp);
    $sRoleName = $aRow[0];
}

// Always fetch all role names when Group Role field is enabled — needed for per-person display
// regardless of whether a specific role filter is active
if (isset($_POST['GroupRoleEnable'])) {
    $rsTemp = RunPreparedQuery('SELECT lst_OptionName,lst_OptionID FROM list_lst WHERE lst_ID = ?', 'i', [(int) $iRoleListID]);

    while ($aRow = mysqli_fetch_array($rsTemp)) {
        $aRoleNames[$aRow[1]] = $aRow[0];
    }
}

$pdf = new PdfGroupDirectory();

// See if this group has special properties.
$rsProps = RunPreparedQuery('SELECT * FROM groupprop_master WHERE grp_ID = ? ORDER BY prop_ID', 'i', [(int) $iGroupID]);
$bHasProps = (mysqli_num_rows($rsProps) > 0);

$sSQL = 'SELECT * FROM person_per
            LEFT JOIN family_fam ON per_fam_ID = fam_ID ';

if ($bHasProps) {
    $sSQL .= 'LEFT JOIN groupprop_' . $iGroupID . ' ON groupprop_' . $iGroupID . '.per_ID = person_per.per_ID ';
}

$sSQL .= 'LEFT JOIN person2group2role_p2g2r ON p2g2r_per_ID = person_per.per_ID
            WHERE p2g2r_grp_ID = ' . $iGroupID;

if ($iRoleID > 0) {
    $sSQL .= ' AND p2g2r_rle_ID = ' . $iRoleID;
}

if ($bOnlyCartMembers && count($_SESSION['aPeopleCart']) > 0) {
    $sSQL .= ' AND person_per.per_ID IN (' . Cart::getCartIdString() . ')';
}

$sSQL .= ' ORDER BY per_LastName';

$rsRecords = RunQuery($sSQL);

while ($aRow = mysqli_fetch_array($rsRecords)) {
    $OutStr = '';

    $pdf->sFamily = MiscUtils::formatFullName($aRow['per_Title'], $aRow['per_FirstName'], $aRow['per_MiddleName'], $aRow['per_LastName'], $aRow['per_Suffix'], 3);

    // Use person data only - each person must enter their own information
    $sAddress1 = $aRow['per_Address1'] ?? '';
    $sAddress2 = $aRow['per_Address2'] ?? '';
    $sCity = $aRow['per_City'] ?? '';
    $sState = $aRow['per_State'] ?? '';
    $sZip = $aRow['per_Zip'] ?? '';
    $sHomePhone = $aRow['per_HomePhone'] ?? '';
    $sWorkPhone = $aRow['per_WorkPhone'] ?? '';
    $sCellPhone = $aRow['per_CellPhone'] ?? '';
    $sEmail = $aRow['per_Email'] ?? '';

    if (isset($_POST['GroupRoleEnable'])) {
        $OutStr = gettext('Role') . ': ' . $aRoleNames[$aRow['p2g2r_rle_ID']] ."\n";
    }

    if (isset($_POST['AddressEnable'])) {
        if (strlen($sAddress1)) {
            $OutStr .= $sAddress1 ."\n";
        }
        if (strlen($sAddress2)) {
            $OutStr .= $sAddress2 ."\n";
        }
        if (strlen($sCity)) {
            $OutStr .= $sCity . ', ' . $sState . ' ' . $sZip ."\n";
        }
    }

    if (isset($_POST['HomePhoneEnable']) && strlen($sHomePhone)) {
        $TempStr = $sHomePhone;
        $OutStr .= '  ' . gettext('Phone') . ': ' . $TempStr ."\n";
    }

    if (isset($_POST['WorkPhoneEnable']) && strlen($sWorkPhone)) {
        $TempStr = $sWorkPhone;
        $OutStr .= '  ' . gettext('Work') . ': ' . $TempStr ."\n";
    }

    if (isset($_POST['CellPhoneEnable']) && strlen($sCellPhone)) {
        $TempStr = $sCellPhone;
        $OutStr .= '  ' . gettext('Cell') . ': ' . $TempStr ."\n";
    }

    if (isset($_POST['EmailEnable']) && strlen($sEmail)) {
        $OutStr .= '  ' . gettext('Email') . ': ' . $sEmail ."\n";
    }

    if (isset($_POST['OtherEmailEnable']) && strlen($aRow['per_WorkEmail'])) {
        $OutStr .= '  ' . gettext('Other Email') . ': ' . $aRow['per_WorkEmail'] .="\n";
    }

    if (isset($_POST['BirthdayEnable'])) {
        $month = (int) ($aRow['per_BirthMonth'] ?? 0);
        $day   = (int) ($aRow['per_BirthDay']   ?? 0);
        $year  = (int) ($aRow['per_BirthYear']  ?? 0);
        if ($month > 0 && $day > 0) {
            $bday = date('F j', mktime(0, 0, 0, $month, $day));
            if ($year > 0) {
                $bday .= ', ' . $year;
            }
            $OutStr .= '  ' . gettext('Birthday') . ': ' . $bday . "\n";
        }
    }

    if (isset($_POST['GenderEnable'])) {
        $gender = (int) ($aRow['per_Gender'] ?? 0);
        if ($gender === 1) {
            $OutStr .= '  ' . gettext('Gender') . ': ' . gettext('Male') . "\n";
        } elseif ($gender === 2) {
            $OutStr .= '  ' . gettext('Gender') . ': ' . gettext('Female') . "\n";
        }
    }

    if ($bHasProps) {
        while ($aPropRow = mysqli_fetch_array($rsProps)) {
            if (isset($_POST[$aPropRow['prop_Field'] . 'enable'])) {
                $currentData = trim($aRow[$aPropRow['prop_Field']]);
                $OutStr .= $aPropRow['prop_Name'] . ': ' . CustomFieldUtils::display($aPropRow['type_ID'], $currentData, $aPropRow['prop_Special']) ."\n";
            }
        }
        mysqli_data_seek($rsProps, 0);
    }

    // Count the number of lines in the output string
    $numlines = 1;
    $offset = 0;
    while ($result = strpos($OutStr,"\n", $offset)) {
        $offset = $result + 1;
        $numlines++;
    }

    $pdf->addRecord($pdf->sFamily, $OutStr, $numlines);
}

if (SystemConfig::getIntValue('iPDFOutputType') === 1) {
    $pdf->Output('GroupDirectory-' . date(SystemConfig::getValue('sDateFilenameFormat')) . '.pdf', 'D');
} else {
    $pdf->Output();
}
