<?php
// generate_agreement.php

// Check if form was submitted
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die('Invalid request method');
}

// Include PhpWord library (manual installation)
require_once 'phpword/src/PhpWord/Autoloader.php';
\PhpOffice\PhpWord\Autoloader::register();

use PhpOffice\PhpWord\TemplateProcessor;

try {
    // Load the template
    $templatePath = 'enrollment_agreement_template.docx';
    
    if (!file_exists($templatePath)) {
        die('Template file not found. Please ensure "enrollment_agreement_template.docx" exists in the same directory.');
    }
    
    $templateProcessor = new TemplateProcessor($templatePath);
    
    // Get form data and sanitize
    $data = [
        'day_date' => getOrdinalDay($_POST['day_date']),
        'month_date' => sanitize($_POST['month_date']),
        'year_date' => sanitize($_POST['year_date']),
        'name' => sanitize($_POST['name']),
        'surname' => sanitize($_POST['surname']),
        'father' => sanitize($_POST['father']),
        'dob' => formatDate($_POST['dob']),
        'pob' => sanitize($_POST['pob']),
        'citizenship' => sanitize($_POST['citizenship']),
        'doc_id' => sanitize($_POST['doc_id']),
        'diploma_nr' => sanitize($_POST['diploma_nr']),
        'address' => sanitize($_POST['address']),
        'personal_phone' => sanitize($_POST['personal_phone']),
        'parent_phone' => sanitize($_POST['parent_phone']),
        'mail' => sanitize($_POST['mail']),
        'study_prog' => sanitize($_POST['study_prog']),
        'faculty_name' => sanitize($_POST['faculty_name']),
        'nr_of_years' => sanitize($_POST['nr_of_years']),
        'yearsNumber_to_text' => numberToWords($_POST['nr_of_years']),
        'ects_number' => sanitize($_POST['ects_number']),
        'ects_to_text' => numberToWords($_POST['ects_number']),
        'issuing_inst' => sanitize($_POST['issuing_inst']),
        'issue_date' => formatDate($_POST['issue_date']),
        'issuing_place' => sanitize($_POST['issuing_place'])
    ];
    
    // Replace placeholders in template
    foreach ($data as $placeholder => $value) {
        $templateProcessor->setValue($placeholder, $value);
    }
    
    // Generate filename: Agreement_StudentName_Date
    $cleanName = preg_replace('/[^a-zA-Z0-9\s]/', '', $data['name'] . '_' . $data['surname']);
    $cleanName = preg_replace('/\s+/', '_', trim($cleanName));
    $filename = 'Agreement_' . $cleanName . '_' . date('Y-m-d') . '.docx';
    
    // Save to temporary file
    $tempFile = 'temp/' . uniqid() . '.docx';
    
    // Create temp directory if it doesn't exist
    if (!file_exists('temp')) {
        mkdir('temp', 0755, true);
    }
    
    $templateProcessor->saveAs($tempFile);
    
    // Clear any previous output
    ob_clean();
    
    // Force download headers
    header('Content-Description: File Transfer');
    header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($tempFile));
    
    // Output file
    readfile($tempFile);
    
    // Clean up temporary file
    unlink($tempFile);
    
    // Redirect back to form
    header('Location: agreement_form.html');
    exit();
    
} catch (Exception $e) {
    die('Error generating document: ' . $e->getMessage());
}

/**
 * Sanitize input data
 */
function sanitize($input) {
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

/**
 * Format date from HTML date input to readable format
 */
function formatDate($dateString) {
    if (empty($dateString)) {
        return '';
    }
    
    $date = DateTime::createFromFormat('Y-m-d', $dateString);
    if ($date) {
        return $date->format('d/m/Y');
    }
    
    return $dateString;
}

/**
 * Convert day number to ordinal format (1st, 2nd, 3rd, etc.)
 */
function getOrdinalDay($day) {
    $day = (int) $day;
    
    if ($day >= 11 && $day <= 13) {
        return $day . 'th';
    }
    
    switch ($day % 10) {
        case 1:
            return $day . 'st';
        case 2:
            return $day . 'nd';
        case 3:
            return $day . 'rd';
        default:
            return $day . 'th';
    }
}

/**
 * Convert number to words
 */
function numberToWords($number) {
    $number = (int) $number;
    
    if ($number == 0) {
        return 'zero';
    }
    
    $ones = array(
        '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
        'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
        'seventeen', 'eighteen', 'nineteen'
    );
    
    $tens = array(
        '', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'
    );
    
    $scales = array('', 'thousand', 'million', 'billion');
    
    return convertNumberToWords($number, $ones, $tens, $scales);
}

/**
 * Helper function to convert integer to words
 */
function convertNumberToWords($number, $ones, $tens, $scales) {
    if ($number < 20) {
        return $ones[$number];
    } elseif ($number < 100) {
        return $tens[intval($number / 10)] . ($number % 10 != 0 ? ' ' . $ones[$number % 10] : '');
    } elseif ($number < 1000) {
        return $ones[intval($number / 100)] . ' hundred' . ($number % 100 != 0 ? ' ' . convertNumberToWords($number % 100, $ones, $tens, $scales) : '');
    } else {
        for ($i = 3; $i >= 1; $i--) {
            $divisor = pow(1000, $i);
            if ($number >= $divisor) {
                return convertNumberToWords(intval($number / $divisor), $ones, $tens, $scales) . ' ' . $scales[$i] . ($number % $divisor != 0 ? ' ' . convertNumberToWords($number % $divisor, $ones, $tens, $scales) : '');
            }
        }
    }
    return '';
}

/**
 * Clean up old temporary files
 */
function cleanupTempFiles() {
    $tempDir = 'temp/';
    if (is_dir($tempDir)) {
        $files = glob($tempDir . '*');
        $now = time();
        
        foreach ($files as $file) {
            if (is_file($file)) {
                // Delete files older than 1 hour
                if ($now - filemtime($file) >= 3600) {
                    unlink($file);
                }
            }
        }
    }
}

// Clean up old files
cleanupTempFiles();
?>