<?php
/**
 * install_libraries.php
 * Automatically downloads and installs PhpSpreadsheet and PHPMailer
 * No Composer or shell access required.
 */

// Disable time limit for large downloads
set_time_limit(300);

// Helper function to download and extract
function downloadAndExtract($url, $extractTo, $sourceFolder) {
    echo "Downloading from: $url<br>";
    $zipFile = __DIR__ . '/temp_' . md5($url) . '.zip';
    
    // Download ZIP
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $zipData = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode !== 200 || $zipData === false) {
        echo "Failed to download from $url<br>";
        return false;
    }
    
    file_put_contents($zipFile, $zipData);
    
    // Extract ZIP
    $zip = new ZipArchive();
    if ($zip->open($zipFile) === true) {
        // Extract only the needed folder (e.g., 'src/')
        $tempExtract = __DIR__ . '/temp_extract';
        if (!is_dir($tempExtract)) mkdir($tempExtract);
        $zip->extractTo($tempExtract);
        $zip->close();
        
        // Find the source folder (e.g., PhpSpreadsheet-master/src)
        $sourcePath = $tempExtract . '/' . $sourceFolder;
        if (!is_dir($sourcePath)) {
            // Try to find any folder ending with $sourceFolder
            $folders = glob($tempExtract . '/*/' . $sourceFolder);
            if (!empty($folders)) $sourcePath = $folders[0];
        }
        
        if (is_dir($sourcePath)) {
            // Remove existing target directory
            $target = __DIR__ . '/' . basename($extractTo);
            if (is_dir($target)) {
                deleteDirectory($target);
            }
            // Copy contents
            rename($sourcePath, $target);
            echo "Installed to: $target<br>";
        } else {
            echo "Source folder '$sourceFolder' not found in extracted zip.<br>";
        }
        
        // Cleanup
        deleteDirectory($tempExtract);
        unlink($zipFile);
        return true;
    } else {
        echo "Failed to extract ZIP<br>";
        unlink($zipFile);
        return false;
    }
}

// Helper to delete a directory recursively
function deleteDirectory($dir) {
    if (!file_exists($dir)) return;
    $files = array_diff(scandir($dir), ['.','..']);
    foreach ($files as $file) {
        $path = $dir . '/' . $file;
        is_dir($path) ? deleteDirectory($path) : unlink($path);
    }
    rmdir($dir);
}

// Create simple autoloader
function createAutoloader() {
    $autoloader = __DIR__ . '/vendor_autoload.php';
    $content = '<?php
/**
 * Simple autoloader for PhpSpreadsheet and PHPMailer
 * Generated by install_libraries.php
 */
spl_autoload_register(function ($class) {
    $prefixes = [
        "PhpOffice\\\\PhpSpreadsheet\\\\" => __DIR__ . "/phpspreadsheet/",
        "PHPMailer\\\\PHPMailer\\\\" => __DIR__ . "/phpmailer/",
    ];
    foreach ($prefixes as $prefix => $base_dir) {
        $len = strlen($prefix);
        if (strncmp($prefix, $class, $len) !== 0) continue;
        $relative_class = substr($class, $len);
        $file = $base_dir . str_replace("\\\\", "/", $relative_class) . ".php";
        if (file_exists($file)) require $file;
    }
});
';
    file_put_contents($autoloader, $content);
    echo "Autoloader created: vendor_autoload.php<br>";
}

// Start installation
echo "<h2>Installing required libraries...</h2>";

// Check if ZipArchive is available
if (!class_exists('ZipArchive')) {
    die("Error: PHP Zip extension is required. Please enable zip extension in php.ini");
}

// Install PhpSpreadsheet
$success = downloadAndExtract(
    'https://github.com/PHPOffice/PhpSpreadsheet/archive/master.zip',
    __DIR__ . '/phpspreadsheet',
    'src'
);

if ($success) {
    echo "✅ PhpSpreadsheet installed successfully.<br>";
} else {
    echo "❌ Failed to install PhpSpreadsheet.<br>";
}

// Install PHPMailer
$success = downloadAndExtract(
    'https://github.com/PHPMailer/PHPMailer/archive/master.zip',
    __DIR__ . '/phpmailer',
    'src'
);

if ($success) {
    echo "✅ PHPMailer installed successfully.<br>";
} else {
    echo "❌ Failed to install PHPMailer.<br>";
}

// Create autoloader
createAutoloader();

echo "<h3>Installation complete!</h3>";
echo "<p>Now update your <strong>functions.php</strong> to require '<strong>vendor_autoload.php</strong>' instead of Composer's autoload.</p>";
echo "<p>Example: <code>require_once __DIR__ . '/vendor_autoload.php';</code></p>";
echo "<p><a href='index.php'>Go to Main Page</a></p>";