<?php
// generate_invitation.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 = 'invitation_template.docx';
    
    if (!file_exists($templatePath)) {
        die('Template file not found. Please ensure "invitation_template.docx" exists in the same directory.');
    }
    
    $templateProcessor = new TemplateProcessor($templatePath);
    
    // Get form data and sanitize
    $data = [
        'name' => sanitize($_POST['name']),
        'surname' => sanitize($_POST['surname']),
        'dob' => formatDateAlbanian($_POST['dob']),
        'birthplace' => sanitize($_POST['birthplace']),
        'citizenship' => sanitize($_POST['citizenship']),
        'passport_nr' => sanitize($_POST['passport_nr']),
        'degree_level' => sanitize($_POST['degree_level']),
        'study_prog' => sanitize($_POST['study_prog']),
        'faculty_name' => sanitize($_POST['faculty_name']),
        'start_date' => formatMonthYear($_POST['start_date']),
        'end_date' => formatMonthYear($_POST['end_date'])
    ];
    
    // Create the stay period string
    $stayPeriod = "Duke filluar nga " . $data['start_date'] . " - " . $data['end_date'];
    
    // Replace placeholders in template
    foreach ($data as $placeholder => $value) {
        $templateProcessor->setValue($placeholder, $value);
    }
    
    // Replace the stay period as a complete string
    $templateProcessor->setValue('stay_period', $stayPeriod);
    
    // Generate filename: Invitation_StudentName_Date
    $cleanName = preg_replace('/[^a-zA-Z0-9\s]/', '', $data['name'] . '_' . $data['surname']);
    $cleanName = preg_replace('/\s+/', '_', trim($cleanName));
    $filename = 'Invitation_' . $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);
    
    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 Albanian format (dd.mm.yyyy)
 */
function formatDateAlbanian($dateString) {
    if (empty($dateString)) {
        return '';
    }
    
    $date = DateTime::createFromFormat('Y-m-d', $dateString);
    if ($date) {
        return $date->format('d.m.Y');
    }
    
    return $dateString;
}

/**
 * Format month input to Albanian month year format
 */
function formatMonthYear($monthString) {
    if (empty($monthString)) {
        return '';
    }
    
    // Parse YYYY-MM format
    $parts = explode('-', $monthString);
    if (count($parts) !== 2) {
        return $monthString;
    }
    
    $year = $parts[0];
    $month = (int)$parts[1];
    
    // Albanian month names
    $albanianMonths = [
        1 => 'janar',
        2 => 'shkurt', 
        3 => 'mars',
        4 => 'prill',
        5 => 'maj',
        6 => 'qershor',
        7 => 'korrik',
        8 => 'gusht',
        9 => 'shtator',
        10 => 'tetor',
        11 => 'nëntor',
        12 => 'dhjetor'
    ];
    
    return $albanianMonths[$month] . ' ' . $year;
}

/**
 * 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();
?>