<?php
// Start the session at the top of the script
session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// ... rest of your code ...

// create_template.php

// Function to recursively copy all files and folders
function recurse_copy($src, $dst) {
    $dir = opendir($src);
    @mkdir($dst, 0755, true);
    while (false !== ($file = readdir($dir))) {
        if (($file != '.') && ($file != '..')) {
            if (is_dir($src . '/' . $file)) {
                recurse_copy($src . '/' . $file, $dst . '/' . $file);
            } else {
                copy($src . '/' . $file, $dst . '/' . $file);
            }
        }
    }
    closedir($dir);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST["templateName"]) && !empty($_POST["templateName"])) {
        $templateName = preg_replace("/[^A-Za-z0-9_\-]/", '_', $_POST["templateName"]);
        $templatesDir = __DIR__ . '/templates';
        $newDirPath = $templatesDir . '/' . $templateName;
        $templateBaseDir = __DIR__ . '/template_base';

        if (!is_dir($templatesDir)) {
            mkdir($templatesDir, 0755, true);
        }

        if (!is_dir($newDirPath)) {
            if (mkdir($newDirPath, 0755)) {
                recurse_copy($templateBaseDir, $newDirPath);

                // Set session variable for success message
                $_SESSION['templateCreation'] = 'success';

                // Redirect to the index page
                header('Location: index.php');
                exit;
            } else {
                // Set session variable for error message
                $_SESSION['templateCreation'] = 'error_creating_directory';
                
                // Redirect to the index page
                header('Location: index.php');
                exit;
            }
        } else {
            // Set session variable for error message
            $_SESSION['templateCreation'] = 'directory_exists';
            
            // Redirect to the index page
            header('Location: index.php');
            exit;
        }
    } else {
        // Set session variable for error message
        $_SESSION['templateCreation'] = 'template_name_required';
        
        // Redirect to the index page
        header('Location: index.php');
        exit;
    }
} else {
    // Redirect to the index page if the script is accessed without a POST request
    header('Location: create_teplate.html');
    exit;
}
?>
