<?php
require_once __DIR__ . '/vendor/autoload.php';
require_once 'connection.php'; // Include your database connection file

use PhpOffice\PhpWord\TemplateProcessor;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Process the form data
    $name = $_POST['name'];
    // var_dump($name);
    // die();
    $fullName = $_POST['full_name'];
    $year = $_POST['year'];
    $designation = $_POST['designation'];
    $department = $_POST['department'];

    // Save the data to the database
    $sql = "INSERT INTO add_experience_letter (name, full_name, year, desgination, department) VALUES (?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    
    if (!$stmt) {
        die("Database query error: " . $conn->error); // Check for errors in the SQL query preparation
    }

    $stmt->bind_param("sssss", $name, $fullName, $year, $designation, $department);
    if (!$stmt->execute()) {
        die("Database query error: " . $stmt->error); // Check for errors in the query execution
    }

    // Load the Word template file
    $templateFile = 'offer_letter.docx';
    $templateProcessor = new TemplateProcessor($templateFile);

    // Replace placeholders in the Word template with the form data
    $templateProcessor->setValue('NAME', $name);
    $templateProcessor->setValue('FULL_NAME', $fullName);
    $templateProcessor->setValue('YEAR', $year);
    $templateProcessor->setValue('DESIGNATION', $designation);
    $templateProcessor->setValue('DEPARTMENT', $department);

    // Save the modified Word file
    $outputFile = 'offer_letter_output.docx';
    $templateProcessor->saveAs($outputFile);

    // Provide the file as a download to the user
    header("Content-Disposition: attachment; filename=\"$outputFile\"");
    readfile($outputFile);

    // Clean up the temporary file
    unlink($outputFile);
    exit();
}
?>