<?php
/**
 * Generate a printable blank child member registration form (.docx).
 */

use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\SimpleType\Jc;

require_once dirname(__DIR__) . '/vendor/autoload.php';

/**
 * Build the child registration form document.
 */
function nazareth_build_child_registration_docx(): PhpWord
{
    $logoPath = ROOT_PATH . '/public/img/logo.png';
    if (!is_file($logoPath)) {
        throw new RuntimeException('Church logo not found at public/img/logo.png');
    }

    $phpWord = new PhpWord();
    $phpWord->setDefaultFontName('Calibri');
    $phpWord->setDefaultFontSize(11);

    $phpWord->addFontStyle('brandTitle', [
        'name' => 'Calibri',
        'size' => 18,
        'bold' => true,
        'color' => 'FFFFFF',
    ]);
    $phpWord->addFontStyle('brandSub', [
        'name' => 'Calibri',
        'size' => 11,
        'color' => 'E2E8F0',
    ]);
    $phpWord->addFontStyle('brandMotto', [
        'name' => 'Calibri',
        'size' => 10,
        'italic' => true,
        'color' => 'FBD38D',
    ]);
    $phpWord->addFontStyle('formTitle', [
        'name' => 'Calibri',
        'size' => 14,
        'bold' => true,
        'color' => '1E3A5F',
    ]);
    $phpWord->addFontStyle('formHint', [
        'name' => 'Calibri',
        'size' => 9,
        'color' => '64748B',
        'italic' => true,
    ]);
    $phpWord->addFontStyle('fieldLabel', [
        'name' => 'Calibri',
        'size' => 10,
        'bold' => true,
        'color' => '334155',
    ]);
    $phpWord->addFontStyle('fieldValue', [
        'name' => 'Calibri',
        'size' => 11,
        'color' => '1E293B',
    ]);
    $phpWord->addFontStyle('photoHint', [
        'name' => 'Calibri',
        'size' => 9,
        'color' => '64748B',
    ]);
    $phpWord->addFontStyle('sigLabel', [
        'name' => 'Calibri',
        'size' => 10,
        'color' => '475569',
    ]);

    $phpWord->addTableStyle('headerBand', [
        'borderSize' => 0,
        'cellMargin' => 100,
        'alignment' => Jc::CENTER,
    ]);
    $phpWord->addTableStyle('formGrid', [
        'borderSize' => 6,
        'borderColor' => 'E2E8F0',
        'cellMargin' => 80,
    ]);

    $lineCell = [
        'borderBottomSize' => 8,
        'borderBottomColor' => '94A3B8',
        'valign' => 'bottom',
    ];
    $photoCell = [
        'borderSize' => 6,
        'borderColor' => 'CBD5E1',
        'valign' => 'center',
    ];

    $section = $phpWord->addSection([
        'marginTop' => 720,
        'marginBottom' => 720,
        'marginLeft' => 900,
        'marginRight' => 900,
    ]);

    // —— Branded header with logo ——
    $header = $section->addTable('headerBand');
    $header->addRow(2200);
    $logoCell = $header->addCell(2200, ['bgColor' => '1E3A5F', 'valign' => 'center']);
    $logoCell->addImage($logoPath, [
        'width' => 72,
        'height' => 72,
        'alignment' => Jc::CENTER,
    ]);
    $textCell = $header->addCell(7600, ['bgColor' => '1E3A5F', 'valign' => 'center']);
    $textCell->addText('PCG · Nazareth Congregation', 'brandTitle', ['alignment' => Jc::LEFT, 'spaceAfter' => 60]);
    $textCell->addText(defined('SITE_FULL_NAME') ? SITE_FULL_NAME : 'Presbyterian Church of Ghana, Nazareth Congregation, La', 'brandSub', ['alignment' => Jc::LEFT, 'spaceAfter' => 40]);
    $textCell->addText(defined('MOTTO') ? MOTTO : 'That They All May Be One', 'brandMotto', ['alignment' => Jc::LEFT]);

    $section->addTextBreak(1);
    $section->addText('Child Member Registration Form', 'formTitle', ['alignment' => Jc::CENTER, 'spaceAfter' => 80]);
    $section->addText(
        'For children only. Complete one form per child. Link the child to their family household so they appear with parents and siblings in the directory.',
        'formHint',
        ['alignment' => Jc::CENTER, 'spaceAfter' => 200]
    );

    // —— Photo + first fields ——
    $top = $section->addTable('formGrid');
    $top->addRow(3200);
    $fieldsCol = $top->addCell(7800);

    $inner = $fieldsCol->addTable('formGrid');
    nazareth_child_docx_field_row($inner, 'Membership number', $lineCell, 1);
    nazareth_child_docx_field_row($inner, 'Title', $lineCell, 1, 2200);
    $row = $inner->addRow();
    $row->addCell(2200)->addText('First name', 'fieldLabel');
    $row->addCell(2600, $lineCell)->addText(' ', 'fieldValue');
    $row->addCell(2200)->addText('Middle name', 'fieldLabel');
    $row->addCell(2600, $lineCell)->addText(' ', 'fieldValue');
    nazareth_child_docx_field_row($inner, 'Last name', $lineCell, 1);
    $row = $inner->addRow();
    $row->addCell(2200)->addText('Gender', 'fieldLabel');
    $row->addCell(2600, $lineCell)->addText(' ', 'fieldValue');
    $row->addCell(2400)->addText('Date of birth', 'fieldLabel');
    $row->addCell(2600, $lineCell)->addText(' ', 'fieldValue');
    $row = $inner->addRow();
    $row->addCell(3200)->addText("Child's phone (if any)", 'fieldLabel');
    $row->addCell(4600, $lineCell)->addText(' ', 'fieldValue');
    $row = $inner->addRow();
    $row->addCell(3200)->addText("Child's email (if any)", 'fieldLabel');
    $row->addCell(4600, $lineCell)->addText(' ', 'fieldValue');

    $photoCol = $top->addCell(2200, $photoCell);
    $photoCol->addTextBreak(1);
    $photoCol->addText('Photograph', ['bold' => true, 'size' => 10, 'color' => '334155'], ['alignment' => Jc::CENTER]);
    $photoCol->addTextBreak(2);
    $photoCol->addText('Passport-style', 'photoHint', ['alignment' => Jc::CENTER]);
    $photoCol->addText('photo here', 'photoHint', ['alignment' => Jc::CENTER]);
    $photoCol->addTextBreak(3);
    $photoCol->addText('Status: Child', ['bold' => true, 'size' => 9, 'color' => '1E3A5F'], ['alignment' => Jc::CENTER]);

    $section->addTextBreak(1);

    // —— Remaining fields ——
    $grid = $section->addTable('formGrid');
    nazareth_child_docx_field_row($grid, 'Baptism date', $lineCell, 1);
    nazareth_child_docx_field_row($grid, 'Household (family name)', $lineCell, 1);
    nazareth_child_docx_multiline_row($grid, 'Home address', $lineCell, 2);
    nazareth_child_docx_field_row($grid, 'Ghana Post digital address', $lineCell, 1);
    nazareth_child_docx_field_row($grid, 'Google Map link', $lineCell, 1);
    $row = $grid->addRow();
    $row->addCell(3800)->addText('Parent or caregiver name', 'fieldLabel');
    $row->addCell(6200, $lineCell)->addText(' ', 'fieldValue');
    $row = $grid->addRow();
    $row->addCell(3800)->addText('Parent or caregiver phone', 'fieldLabel');
    $row->addCell(6200, $lineCell)->addText(' ', 'fieldValue');
    nazareth_child_docx_multiline_row($grid, 'Notes', $lineCell, 2);

    $section->addTextBreak(1);
    $sig = $section->addTable('formGrid');
    $row = $sig->addRow();
    $row->addCell(5000)->addText('Parent / guardian signature', 'sigLabel');
    $row->addCell(2500, $lineCell)->addText(' ', 'fieldValue');
    $row->addCell(1500)->addText('Date', 'sigLabel');
    $row->addCell(2500, $lineCell)->addText(' ', 'fieldValue');
    $row = $sig->addRow();
    $row->addCell(5000)->addText('Received by (church staff)', 'sigLabel');
    $row->addCell(2500, $lineCell)->addText(' ', 'fieldValue');
    $row->addCell(1500)->addText('Date', 'sigLabel');
    $row->addCell(2500, $lineCell)->addText(' ', 'fieldValue');

    $section->addTextBreak(1);
    $section->addText(
        'Return completed form to the church office for entry into the membership system.',
        ['size' => 9, 'color' => '94A3B8', 'italic' => true],
        ['alignment' => Jc::CENTER]
    );

    return $phpWord;
}

/**
 * Build and stream the child registration form as a Word document.
 */
function nazareth_send_child_registration_docx(): void
{
    try {
        $phpWord = nazareth_build_child_registration_docx();
    } catch (RuntimeException $e) {
        http_response_code(500);
        echo htmlspecialchars($e->getMessage());
        exit;
    }

    $filename = 'child-registration-form-' . date('Y-m-d') . '.docx';
    header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Cache-Control: max-age=0');

    $writer = IOFactory::createWriter($phpWord, 'Word2007');
    $writer->save('php://output');
    exit;
}

/**
 * @param \PhpOffice\PhpWord\Element\Table $table
 * @param array<string, mixed> $lineCell
 */
function nazareth_child_docx_field_row($table, string $label, array $lineCell, int $labelSpan = 1, int $labelWidth = 3200): void
{
    $row = $table->addRow();
    $row->addCell($labelWidth)->addText($label, 'fieldLabel');
    $valueWidth = 10000 - $labelWidth;
    $row->addCell($valueWidth, $lineCell)->addText(' ', 'fieldValue');
}

/**
 * @param \PhpOffice\PhpWord\Element\Table $table
 * @param array<string, mixed> $lineCell
 */
function nazareth_child_docx_multiline_row($table, string $label, array $lineCell, int $lines = 2): void
{
    $row = $table->addRow($lines * 360);
    $row->addCell(3200, ['valign' => 'top'])->addText($label, 'fieldLabel');
    $cell = $row->addCell(6800, array_merge($lineCell, ['valign' => 'top']));
    for ($i = 0; $i < $lines; $i++) {
        $cell->addText(' ', 'fieldValue');
        if ($i < $lines - 1) {
            $cell->addTextBreak(1);
        }
    }
}
