<?php
/**
 * Manual Template Sync Script
 * 
 * This script scans your physical /templates folder and ensures
 * all landing page files are registered in the SonicPesa database.
 * Use this after manually uploading templates via FTP/cPanel.
 */

session_start();
require_once 'config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';

// Ensure only admins can run this
require_login();
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    die("<h2 style='color:red;'>Access Denied. Super Admins only.</h2>");
}

echo "<html><head><title>Template Sync Tool</title><style>body{font-family:sans-serif; background:#f4f7f6; padding:2rem;} .box{background:#fff; padding:2rem; border-radius:10px; box-shadow:0 10px 30px rgba(0,0,0,0.05); max-width:600px; margin:auto;}</style></head><body>";
echo "<div class='box'>";
echo "<h2 style='color:#4f46e5; margin-top:0;'>SonicPesa Template Synchronizer</h2>";
echo "<p>Scanning <code>/templates</code> directory for new files...</p>";

$templatesDir = __DIR__ . '/templates/';
$addedCount = 0;
$existingCount = 0;

if (is_dir($templatesDir)) {
    $files = scandir($templatesDir);
    
    foreach ($files as $file) {
        // Look specifically for files like landingX.php
        if (strpos($file, 'landing') === 0 && strpos($file, '.php') !== false) {
            $slug = str_replace('.php', '', $file);
            
            // Extract the number from the slug for naming (e.g., landing12 -> 12)
            $num = (int)str_replace('landing', '', $slug);
            $name = $num > 0 ? "Model V" . $num : "Custom " . ucfirst($slug);
            
            // Check if it already exists in the database
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM templates WHERE slug = ?");
            $stmt->execute([$slug]);
            $exists = $stmt->fetchColumn();
            
            if (!$exists) {
                // If the template is landing1 through landing8, we might name it differently,
                // but the DB handles it perfectly fine.
                try {
                    $insert = $pdo->prepare("INSERT INTO templates (name, slug) VALUES (?, ?)");
                    $insert->execute([$name, $slug]);
                    echo "<p style='color:green;'>✅ Successfully registered: <b>{$slug}.php</b> as '{$name}'</p>";
                    $addedCount++;
                } catch (PDOException $e) {
                    echo "<p style='color:red;'>❌ Failed to register <b>{$slug}.php</b>: " . $e->getMessage() . "</p>";
                }
            } else {
                echo "<p style='color:gray;'>⏭️ Skipped: <b>{$slug}.php</b> (Already in database)</p>";
                $existingCount++;
            }
        }
    }
} else {
    echo "<p style='color:red;'>Error: Could not locate the /templates/ directory.</p>";
}

echo "<hr style='border:0; border-top:1px solid #ddd; margin: 1.5rem 0;'>";
echo "<h3>Sync Complete!</h3>";
echo "<ul>";
echo "<li><b>New Templates Added:</b> {$addedCount}</li>";
echo "<li><b>Existing Templates Skipped:</b> {$existingCount}</li>";
echo "</ul>";
echo "<a href='superadmin.php?tab=templates' style='display:inline-block; margin-top:1rem; padding:10px 20px; background:#4f46e5; color:#fff; text-decoration:none; border-radius:8px; font-weight:bold;'>Return to Superadmin</a>";
echo "</div></body></html>";
?>

