<?php
// generate_invoice.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 = 'tuition_invoice_template.docx';
    
    if (!file_exists($templatePath)) {
        die('Template file not found. Please ensure "tuition_invoice_template.docx" exists in the same directory.');
    }
    
    $templateProcessor = new TemplateProcessor($templatePath);
    
    // Invoice number: just the number entered (2-4 digits)
    $invoiceNr = sanitize($_POST['invoice_number']);
    
    // Generate reference number: StudentName + InvoiceNumber (no spaces)
    $cleanStudentName = preg_replace('/[^a-zA-Z0-9]/', '', $_POST['student_name']);
    $refNo = $cleanStudentName . $_POST['invoice_number'];
    
    // Calculate validity date: 7 days from invoice date
    $invoiceDate = DateTime::createFromFormat('Y-m-d', $_POST['date']);
    $validityDate = clone $invoiceDate;
    $validityDate->add(new DateInterval('P7D')); // Add 7 days
    
    // Get form data and sanitize
    $data = [
        'student_name' => sanitize($_POST['student_name']),
        'nationality' => sanitize($_POST['nationality']),
        'email' => sanitize($_POST['email']),
        'phone_nr' => sanitize($_POST['phone_nr']),
        'study_prog' => sanitize($_POST['study_prog']),
        'level' => sanitize($_POST['level']),
        'academic_year' => sanitize($_POST['academic_year']),
        'start_Date' => formatDate($_POST['start_Date']),
        'invoice_nr' => $invoiceNr,
        'date' => formatDate($_POST['date']),
        'validity_date' => $validityDate->format('d/m/Y'),
        'amount' => sanitize($_POST['amount']),
        'amt_to_txt' => numberToWords($_POST['amount']),
        'installment_nr' => sanitize($_POST['installment_nr']),
        'ref_no' => $refNo
    ];
    
    // Replace placeholders in template
    foreach ($data as $placeholder => $value) {
        $templateProcessor->setValue($placeholder, $value);
    }
    
    // Generate filename: Invoice_StudentName_InvoiceNumber
    $cleanName = preg_replace('/[^a-zA-Z0-9\s]/', '', $data['student_name']);
    $cleanName = preg_replace('/\s+/', '_', trim($cleanName));
    $filename = 'Invoice_' . $cleanName . '_' . $_POST['invoice_number'] . '.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: invoice_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 number to words
 */
function numberToWords($number) {
    $number = (float) $number;
    
    if ($number == 0) {
        return 'zero euros';
    }
    
    $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');
    
    // Handle decimals (cents)
    $parts = explode('.', number_format($number, 2, '.', ''));
    $euros = (int) $parts[0];
    $cents = isset($parts[1]) ? (int) $parts[1] : 0;
    
    $result = '';
    
    if ($euros > 0) {
        $result = convertNumberToWords($euros, $ones, $tens, $scales);
        $result .= ($euros == 1) ? ' euro' : ' euros';
    }
    
    if ($cents > 0) {
        if ($euros > 0) {
            $result .= ' and ';
        }
        $result .= convertNumberToWords($cents, $ones, $tens, $scales);
        $result .= ($cents == 1) ? ' cent' : ' cents';
    }
    
    return $result;
}

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