#!/usr/bin/env php
<?php
/**
 * AI-Native CMS - Create Site CLI Tool
 * Creates a new site from an industry preset
 * 
 * Usage: php cli/create-site.php --preset=lawyer --name="Client Name" [--color=#hex]
 */

// Ensure CLI execution
if (php_sapi_name() !== 'cli') {
    die(json_encode(['success' => false, 'error' => 'CLI only']));
}

// Parse command line arguments
$options = getopt('', ['preset:', 'name:', 'color:', 'output:', 'help']);

// Show help
if (isset($options['help']) || empty($options)) {
    echo <<<HELP
AI-Native CMS - Site Creator

Usage:
  php cli/create-site.php --preset=<preset> --name="<name>" [options]

Required:
  --preset    Industry preset (lawyer, clinic, realtor, restaurant, pedagogue)
  --name      Client/business name

Options:
  --color     Primary brand color (hex, e.g., #1a1a2e)
  --output    Output directory (default: ./projects/<slug>)
  --help      Show this help message

Examples:
  php cli/create-site.php --preset=lawyer --name="Smith & Associates"
  php cli/create-site.php --preset=clinic --name="City Health" --color="#0ea5e9"

HELP;
    exit(0);
}

// Validate required arguments
if (empty($options['preset'])) {
    output(['success' => false, 'error' => 'Missing required parameter: --preset']);
}

if (empty($options['name'])) {
    output(['success' => false, 'error' => 'Missing required parameter: --name']);
}

$preset = strtolower($options['preset']);
$name = $options['name'];
$color = $options['color'] ?? '#1a1a2e';
$slug = slugify($name);
$outputDir = $options['output'] ?? __DIR__ . '/../projects/' . $slug;

// Available presets
$validPresets = ['lawyer', 'clinic', 'realtor', 'restaurant', 'pedagogue'];
if (!in_array($preset, $validPresets)) {
    output(['success' => false, 'error' => "Invalid preset: $preset. Valid: " . implode(', ', $validPresets)]);
}

// Check preset directory
$presetDir = __DIR__ . '/../presets/' . $preset;
if (!is_dir($presetDir)) {
    output(['success' => false, 'error' => "Preset directory not found: $presetDir"]);
}

echo "Creating site: $name\n";
echo "Preset: $preset\n";
echo "Output: $outputDir\n";
echo "Color: $color\n\n";

// Create project directory structure
$dirs = [
    $outputDir,
    $outputDir . '/public',
    $outputDir . '/public/admin',
    $outputDir . '/public/uploads',
    $outputDir . '/themes',
    $outputDir . '/themes/default',
    $outputDir . '/themes/default/components',
    $outputDir . '/themes/default/layouts',
    $outputDir . '/src',
    $outputDir . '/cache',
];

foreach ($dirs as $dir) {
    if (!is_dir($dir)) {
        mkdir($dir, 0755, true);
        echo "Created: $dir\n";
    }
}

// Copy core files
$coreDir = __DIR__ . '/..';
$filesToCopy = [
    'public/index.php',
    'public/.htaccess',
    'composer.json',
    'database.sql',
];

foreach ($filesToCopy as $file) {
    $src = $coreDir . '/' . $file;
    $dst = $outputDir . '/' . $file;
    if (file_exists($src)) {
        copy($src, $dst);
        echo "Copied: $file\n";
    }
}

// Copy directories recursively
$dirsToCopy = [
    'public/admin' => 'public/admin',
    'src' => 'src',
    'themes/default' => 'themes/default',
];

foreach ($dirsToCopy as $srcDir => $dstDir) {
    $src = $coreDir . '/' . $srcDir;
    $dst = $outputDir . '/' . $dstDir;
    if (is_dir($src)) {
        copyDirectory($src, $dst);
        echo "Copied directory: $srcDir\n";
    }
}

// Create fresh database
$dbPath = $outputDir . '/database.sqlite';
$sqlPath = $coreDir . '/database.sql';

if (file_exists($sqlPath)) {
    // Create empty database
    $db = new SQLite3($dbPath);

    // Execute schema
    $sql = file_get_contents($sqlPath);
    $db->exec($sql);

    // Insert default admin user
    $db->exec("INSERT OR IGNORE INTO users (username, password, email, role) VALUES ('admin', '" . password_hash('admin123', PASSWORD_DEFAULT) . "', 'admin@example.com', 'admin')");

    // Insert site settings
    $siteName = $db->escapeString($name);
    $db->exec("INSERT OR REPLACE INTO settings (key, value) VALUES ('site_name', '$siteName')");
    $db->exec("INSERT OR REPLACE INTO settings (key, value) VALUES ('brand_color', '$color')");

    echo "Created database: $dbPath\n";

    // Load preset pages
    $pagesFile = $presetDir . '/pages.json';
    if (file_exists($pagesFile)) {
        $pages = json_decode(file_get_contents($pagesFile), true);
        if ($pages) {
            foreach ($pages as $page) {
                $title = $db->escapeString(str_replace('{name}', $name, $page['title']));
                $slug = $db->escapeString($page['slug']);
                $content = $db->escapeString(str_replace('{name}', $name, $page['content']));
                $template = $db->escapeString($page['template'] ?? 'page');

                $db->exec("INSERT INTO pages (title, slug, content, template, status, created_at) VALUES ('$title', '$slug', '$content', '$template', 'published', datetime('now'))");
                echo "Created page: {$page['title']}\n";
            }
        }
    }

    $db->close();
}

// Create .env file
$envContent = <<<ENV
APP_NAME="{$name}"
APP_ENV=production
APP_DEBUG=false
ENV;

file_put_contents($outputDir . '/.env', $envContent);
echo "Created: .env\n";

// Update brand color in theme CSS if exists
$cssFile = $outputDir . '/themes/default/style.css';
if (file_exists($cssFile)) {
    $css = file_get_contents($cssFile);
    $css = preg_replace('/--primary:\s*#[a-fA-F0-9]{6}/', "--primary: $color", $css);
    file_put_contents($cssFile, $css);
    echo "Updated brand color in CSS\n";
}

echo "\n✅ Site created successfully!\n";
echo "Path: $outputDir\n\n";
echo "Next steps:\n";
echo "  1. cd $outputDir\n";
echo "  2. php -S localhost:8000 -t public\n";
echo "  3. Open http://localhost:8000/admin (admin/admin123)\n";

output(['success' => true, 'message' => 'Site created', 'path' => $outputDir, 'name' => $name, 'preset' => $preset]);

// ============ Helper Functions ============

function output($data)
{
    if (defined('JSON_OUTPUT') && JSON_OUTPUT) {
        echo json_encode($data);
    }
    exit($data['success'] ? 0 : 1);
}

function slugify($text)
{
    $text = preg_replace('~[^\pL\d]+~u', '-', $text);
    $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
    $text = preg_replace('~[^-\w]+~', '', $text);
    $text = trim($text, '-');
    $text = preg_replace('~-+~', '-', $text);
    $text = strtolower($text);
    return $text ?: 'project';
}

function copyDirectory($src, $dst)
{
    $dir = opendir($src);
    @mkdir($dst, 0755, true);
    while (($file = readdir($dir)) !== false) {
        if ($file != '.' && $file != '..') {
            if (is_dir($src . '/' . $file)) {
                copyDirectory($src . '/' . $file, $dst . '/' . $file);
            } else {
                copy($src . '/' . $file, $dst . '/' . $file);
            }
        }
    }
    closedir($dir);
}
