<?php
// generate_letter.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 = 'admission_letter_template.docx';
   
   if (!file_exists($templatePath)) {
       die('Template file not found. Please ensure "admission_letter_template.docx" exists in the same directory.');
   }
   
   $templateProcessor = new TemplateProcessor($templatePath);
   
   // Get form data and sanitize - MATCH the template variable names exactly
   $data = [
       'day_date' => sanitize($_POST['day_date']),
       'month_date' => sanitize($_POST['month_date']),
       'year_date' => sanitize($_POST['year']),
       'ref_no' => sanitize($_POST['ref_no']),
       'to_recipient' => sanitize($_POST['to_recipient']),
       'dob' => formatDate($_POST['dob']),
       'citizenship' => sanitize($_POST['citizenship']),
       'recipient_name' => sanitize($_POST['recipient_name']),
       'study_prog' => sanitize($_POST['study_prog']),
       'level' => sanitize($_POST['level']),
       'duration' => sanitize($_POST['duration']),
       'fee' => sanitize($_POST['fee'])
   ];
   
   // Replace placeholders in template
   foreach ($data as $placeholder => $value) {
       $templateProcessor->setValue($placeholder, $value);
   }
   
   // Generate filename: CAL ${recipient_name} ${ref_no}
   $cleanName = preg_replace('/[^a-zA-Z0-9\s]/', '', $data['recipient_name']);
   $cleanName = preg_replace('/\s+/', '_', trim($cleanName));
   $cleanRefNo = preg_replace('/[^a-zA-Z0-9]/', '', $data['ref_no']);
   $filename = 'CAL_' . $cleanName . '_' . $cleanRefNo . '.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: index1.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;
}

/**
* Clean up old temporary files (optional - run this periodically)
*/
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();
?>