<?php
/**
 * JDS Billing System - Installation Wizard
 * Version 2.0 with License Validation
 *
 * This installer requires a valid license before proceeding with installation.
 * License is verified against the server at https://ncs.nanzige.com
 */

session_start();

// Set longer execution time and memory limit for large SQL operations
set_time_limit(0);
ini_set('memory_limit', '1024M');
ini_set('max_execution_time', 0);
ini_set('max_input_time', 0);

// Define paths
define('INSTALLER_LOCK_FILE', __DIR__ . '/../../install.lock');
define('LICENSE_LOCK_FILE', __DIR__ . '/../../license.lock');
define('LICENSE_SERVER_URL', 'https://khatali.jasiridynamics.com/api/verify-license.php');

// Check if installation is locked
if (file_exists(INSTALLER_LOCK_FILE)) {
    showLockedPage();
    exit;
}

// Include database library
require_once 'includes/databaseLibrary.php';

// Auto-detect domain and base URL
function getAutoDetectedUrl() {
    $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $host = $_SERVER['HTTP_HOST'];
    $requestUri = $_SERVER['REQUEST_URI'];

    $setupPos = strpos($requestUri, '/setup/install/');
    if ($setupPos !== false) {
        $basePath = substr($requestUri, 0, $setupPos);
    } else {
        $setupPos = strpos($requestUri, '/setup/install');
        if ($setupPos !== false) {
            $basePath = substr($requestUri, 0, $setupPos);
        } else {
            $basePath = dirname($requestUri);
        }
    }

    $basePath = rtrim($basePath, '/');
    if (empty($basePath) || $basePath === '.' || $basePath === '/') {
        $basePath = '';
    } else {
        $basePath = '/' . ltrim($basePath, '/');
    }

    $fullUrl = $protocol . $host . $basePath;
    if ($basePath !== '') {
        $fullUrl = rtrim($fullUrl, '/');
    }

    return $fullUrl;
}

/**
 * Generate unique system fingerprint
 */
function generateSystemId() {
    $data = [];

    // Server-specific data
    $data[] = $_SERVER['SERVER_NAME'] ?? 'unknown';
    $data[] = $_SERVER['DOCUMENT_ROOT'] ?? 'unknown';
    $data[] = php_uname('n'); // Hostname
    $data[] = php_uname('s'); // OS name

    // PHP installation specific
    $data[] = PHP_VERSION;
    $data[] = __DIR__;

    // Database path (unique per installation)
    $data[] = realpath(__DIR__ . '/../../');

    // Create hash
    return hash('sha256', implode('|', $data));
}

/**
 * Get server information for license activation
 */
function getServerInfo() {
    return [
        'php_version' => PHP_VERSION,
        'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? 'unknown',
        'document_root' => $_SERVER['DOCUMENT_ROOT'] ?? 'unknown',
        'server_name' => $_SERVER['SERVER_NAME'] ?? 'unknown',
        'os' => php_uname('s') . ' ' . php_uname('r'),
        'hostname' => php_uname('n'),
        'install_path' => realpath(__DIR__ . '/../../')
    ];
}

/**
 * Verify license with server
 */
function verifyLicense($licenseKey, $name, $email, $domain) {
    $systemId = generateSystemId();
    $serverInfo = getServerInfo();

    $postData = json_encode([
        'action' => 'verify',
        'license_key' => $licenseKey,
        'name' => $name,
        'email' => $email,
        'system_id' => $systemId,
        'domain' => $domain,
        'server_info' => $serverInfo
    ]);

    // Initialize cURL
    $ch = curl_init(LICENSE_SERVER_URL);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $postData,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Accept: application/json'
        ],
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    if ($error) {
        return [
            'success' => false,
            'message' => 'Could not connect to license server. Please check your internet connection.',
            'error' => $error
        ];
    }

    $result = json_decode($response, true);

    if (!$result) {
        return [
            'success' => false,
            'message' => 'Invalid response from license server.'
        ];
    }

    if ($result['status'] === 'valid') {
        return [
            'success' => true,
            'message' => $result['message'],
            'data' => $result['data']
        ];
    }

    return [
        'success' => false,
        'message' => $result['message'] ?? 'License verification failed.',
        'code' => $result['code'] ?? 'UNKNOWN_ERROR'
    ];
}

/**
 * Create license lock file
 */
function createLicenseLock($licenseData) {
    $lockData = [
        'license_key' => $licenseData['license_key'],
        'name' => $licenseData['name'],
        'email' => $licenseData['email'],
        'license_type' => $licenseData['license_type'],
        'license_type_name' => $licenseData['license_type_name'],
        'system_id' => $licenseData['system_id'],
        'domain' => $licenseData['domain'],
        'expiry_date' => $licenseData['expiry_date'],
        'is_lifetime' => $licenseData['is_lifetime'],
        'activated_at' => $licenseData['activated_at'],
        'integrity_hash' => $licenseData['integrity_hash'],
        'features' => $licenseData['features'],
        'created_at' => date('Y-m-d H:i:s')
    ];

    // Add verification checksum
    $lockData['checksum'] = hash('sha256', json_encode($lockData) . 'NCS_LICENSE_LOCK_SECRET');

    $content = "<?php\n";
    $content .= "// NCS Billing System - License Lock File\n";
    $content .= "// DO NOT MODIFY OR DELETE THIS FILE\n";
    $content .= "// Generated: " . date('Y-m-d H:i:s') . "\n\n";
    $content .= "if (!defined('NCS_BILLING')) { exit('Direct access not allowed'); }\n\n";
    $content .= "return " . var_export($lockData, true) . ";\n";

    return file_put_contents(LICENSE_LOCK_FILE, $content) !== false;
}

/**
 * Create default trial license lock file
 * This is automatically created after installation if no license was provided
 */
function createDefaultTrialLicense($domain) {
    $systemId = generateSystemId();
    $activatedAt = date('Y-m-d H:i:s');
    // Trial license valid for 30 days
    $expiryDate = date('Y-m-d H:i:s', strtotime('+30 days'));
    
    $lockData = [
        'license_key' => 'TRIAL-' . strtoupper(substr(md5($systemId . time()), 0, 15)),
        'name' => 'Trial User',
        'email' => 'trial@ncsbilling.local',
        'license_type' => 'trial',
        'license_type_name' => 'Trial License',
        'system_id' => $systemId,
        'domain' => $domain,
        'expiry_date' => $expiryDate,
        'is_lifetime' => false,
        'activated_at' => $activatedAt,
        'integrity_hash' => hash('sha256', $systemId . $domain . $activatedAt),
        'features' => [
            'premium' => true,
            'max_users' => 5,
            'api_access' => true,
            'support_priority' => 'trial',
        ],
        'created_at' => date('Y-m-d H:i:s')
    ];

    // Add verification checksum
    $lockData['checksum'] = hash('sha256', json_encode($lockData) . 'NCS_LICENSE_LOCK_SECRET');

    $content = "<?php\n";
    $content .= "// NCS Billing System - License Lock File\n";
    $content .= "// DO NOT MODIFY OR DELETE THIS FILE\n";
    $content .= "// Auto-generated Trial License\n";
    $content .= "// Generated: " . date('Y-m-d H:i:s') . "\n\n";
    $content .= "if (!defined('NCS_BILLING')) { exit('Direct access not allowed'); }\n\n";
    $content .= "return " . var_export($lockData, true) . ";\n";

    return file_put_contents(LICENSE_LOCK_FILE, $content) !== false;
}

$urlWb = getAutoDetectedUrl();

// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');

    $action = $_POST['action'];
    $response = ['success' => false, 'message' => '', 'step' => 0, 'progress' => 0];

    // Sanitize all POST data
    $cleanData = [];
    foreach ($_POST as $key => $value) {
        if ($key !== 'action') {
            $cleanData[$key] = htmlspecialchars(strip_tags(trim($value)), ENT_QUOTES, 'UTF-8');
        }
    }

    try {
        switch ($action) {
            case 'verify_license':
                $response = handleLicenseVerification($cleanData);
                break;
            case 'validate_database':
                // Check if license is verified first
                if (!file_exists(LICENSE_LOCK_FILE)) {
                    $response = ['success' => false, 'message' => 'License must be verified first.', 'step' => 1, 'progress' => 0];
                    break;
                }
                $response = validateDatabase($cleanData);
                break;
            case 'create_database':
                if (!file_exists(LICENSE_LOCK_FILE)) {
                    $response = ['success' => false, 'message' => 'License must be verified first.', 'step' => 1, 'progress' => 0];
                    break;
                }
                $response = createDatabase($cleanData);
                break;
            case 'install_tables':
                if (!file_exists(LICENSE_LOCK_FILE)) {
                    $response = ['success' => false, 'message' => 'License must be verified first.', 'step' => 1, 'progress' => 0];
                    break;
                }
                $response = installTables($cleanData);
                break;
            case 'create_admin':
                if (!file_exists(LICENSE_LOCK_FILE)) {
                    $response = ['success' => false, 'message' => 'License must be verified first.', 'step' => 1, 'progress' => 0];
                    break;
                }
                $response = createAdminUser($cleanData);
                break;
            case 'finalize':
                // Auto-create trial license if none exists
                if (!file_exists(LICENSE_LOCK_FILE)) {
                    global $urlWb;
                    if (!createDefaultTrialLicense($urlWb)) {
                        $response = ['success' => false, 'message' => 'Failed to create default license file.', 'step' => 6, 'progress' => 85];
                        break;
                    }
                }
                $response = finalizeInstallation($cleanData);
                break;
            default:
                $response['message'] = 'Invalid action';
        }
    } catch (Exception $e) {
        $response['message'] = 'Error: ' . $e->getMessage();
        error_log("Installation error: " . $e->getMessage());
    }

    echo json_encode($response);
    exit;
}

/**
 * Handle license verification step
 */
function handleLicenseVerification($data) {
    global $urlWb;

    $licenseKey = $data['license_key'] ?? '';
    $name = $data['license_name'] ?? '';
    $email = $data['license_email'] ?? '';

    if (empty($licenseKey)) {
        return ['success' => false, 'message' => 'License key is required.', 'step' => 1, 'progress' => 0];
    }
    if (empty($name)) {
        return ['success' => false, 'message' => 'Customer name is required.', 'step' => 1, 'progress' => 0];
    }
    if (empty($email)) {
        return ['success' => false, 'message' => 'Customer email is required.', 'step' => 1, 'progress' => 0];
    }
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return ['success' => false, 'message' => 'Invalid email format.', 'step' => 1, 'progress' => 0];
    }

    // Verify license with server
    $result = verifyLicense($licenseKey, $name, $email, $urlWb);

    if (!$result['success']) {
        return [
            'success' => false,
            'message' => $result['message'],
            'step' => 1,
            'progress' => 0
        ];
    }

    // Create license lock file
    $licenseData = $result['data'];
    $licenseData['domain'] = $urlWb;

    if (!createLicenseLock($licenseData)) {
        return [
            'success' => false,
            'message' => 'Failed to save license information. Please check file permissions.',
            'step' => 1,
            'progress' => 0
        ];
    }

    // Store license info in session for display
    $_SESSION['license_info'] = [
        'name' => $licenseData['name'],
        'email' => $licenseData['email'],
        'license_type' => $licenseData['license_type_name'],
        'expiry_date' => $licenseData['expiry_date'],
        'is_lifetime' => $licenseData['is_lifetime']
    ];

    return [
        'success' => true,
        'message' => 'License verified and activated successfully!',
        'step' => 2,
        'progress' => 15,
        'license_info' => [
            'type' => $licenseData['license_type_name'],
            'expiry' => $licenseData['is_lifetime'] ? 'Never (Lifetime)' : $licenseData['expiry_date'],
            'name' => $licenseData['name']
        ]
    ];
}

function validateDatabase($data) {
    $host = $data['hostname'] ?? 'localhost';
    $username = $data['username'] ?? 'root';
    $password = $data['password'] ?? '';
    $database = $data['database'] ?? 'ncs';

    $connection = @mysqli_connect($host, $username, $password);

    if (!$connection) {
        return [
            'success' => false,
            'message' => 'Failed to connect to database server. Please check your credentials.',
            'step' => 2,
            'progress' => 15
        ];
    }

    mysqli_close($connection);

    return [
        'success' => true,
        'message' => 'Database connection successful!',
        'step' => 3,
        'progress' => 30
    ];
}

function createDatabase($data) {
    $host = $data['hostname'] ?? 'localhost';
    $username = $data['username'] ?? 'root';
    $password = $data['password'] ?? '';
    $database = $data['database'] ?? 'ncs';

    $connection = @mysqli_connect($host, $username, $password);

    if (!$connection) {
        return [
            'success' => false,
            'message' => 'Failed to connect to database server.',
            'step' => 3,
            'progress' => 30
        ];
    }

    $result = mysqli_query($connection, "CREATE DATABASE IF NOT EXISTS `$database`");

    if (!$result) {
        mysqli_close($connection);
        return [
            'success' => false,
            'message' => 'Failed to create database: ' . mysqli_error($connection),
            'step' => 3,
            'progress' => 30
        ];
    }

    mysqli_close($connection);

    return [
        'success' => true,
        'message' => 'Database created successfully!',
        'step' => 4,
        'progress' => 45
    ];
}

function installTables($data) {
    $host = $data['hostname'] ?? 'localhost';
    $username = $data['username'] ?? 'root';
    $password = $data['password'] ?? '';
    $database = $data['database'] ?? 'ncs';

    $connection = @mysqli_connect($host, $username, $password, $database);

    if (!$connection) {
        return [
            'success' => false,
            'message' => 'Failed to connect to database.',
            'step' => 4,
            'progress' => 45
        ];
    }

    mysqli_query($connection, "SET SESSION wait_timeout = 600");
    mysqli_query($connection, "SET SESSION interactive_timeout = 600");

    $sqlFile = 'billing.sql';
    $sqlContent = file_get_contents($sqlFile);

    if ($sqlContent === false) {
        mysqli_close($connection);
        return [
            'success' => false,
            'message' => 'Failed to read SQL file.',
            'step' => 4,
            'progress' => 45
        ];
    }

    $result = mysqli_multi_query($connection, $sqlContent);

    if ($result) {
        while (mysqli_more_results($connection)) {
            mysqli_next_result($connection);
        }

        mysqli_close($connection);
        return [
            'success' => true,
            'message' => 'Database tables installed successfully!',
            'step' => 5,
            'progress' => 70
        ];
    } else {
        $error = mysqli_error($connection);
        mysqli_close($connection);
        return [
            'success' => false,
            'message' => 'Failed to install database tables: ' . $error,
            'step' => 4,
            'progress' => 45
        ];
    }
}

function createAdminUser($data) {
    $host = $data['hostname'] ?? 'localhost';
    $username = $data['username'] ?? 'root';
    $password = $data['password'] ?? '';
    $database = $data['database'] ?? 'ncs';

    $adminEmail = 'admin@example.com';
    $adminPassword = '123456';

    $connection = @mysqli_connect($host, $username, $password, $database);

    if (!$connection) {
        return [
            'success' => false,
            'message' => 'Failed to connect to database.',
            'step' => 5,
            'progress' => 70
        ];
    }

    $adminEmail = mysqli_real_escape_string($connection, $adminEmail);
    $hashedPassword = password_hash($adminPassword, PASSWORD_DEFAULT);
    $hashedPassword = mysqli_real_escape_string($connection, $hashedPassword);

    $updateQuery = "UPDATE `db_users` SET `email` = '$adminEmail', `password` = '$hashedPassword' WHERE `id` = '1'";

    if (mysqli_query($connection, $updateQuery)) {
        mysqli_close($connection);
        return [
            'success' => true,
            'message' => 'Admin user configured with default credentials!',
            'step' => 6,
            'progress' => 85
        ];
    } else {
        $error = mysqli_error($connection);
        mysqli_close($connection);
        return [
            'success' => false,
            'message' => 'Failed to create admin user: ' . $error,
            'step' => 5,
            'progress' => 70
        ];
    }
}

function finalizeInstallation($data) {
    $host = $data['hostname'] ?? 'localhost';
    $username = $data['username'] ?? 'root';
    $password = $data['password'] ?? '';
    $database = $data['database'] ?? 'ncs';
    $siteUrl = $data['site_url'] ?? '';

    $connection = @mysqli_connect($host, $username, $password, $database);

    if (!$connection) {
        return [
            'success' => false,
            'message' => 'Failed to connect to database.',
            'step' => 6,
            'progress' => 85
        ];
    }

    $siteUrl = mysqli_real_escape_string($connection, $siteUrl);

    $updateQuery = "UPDATE `db_sitesettings` SET `domain` = '$siteUrl', `version` = '3.6' WHERE `id` = '1'";

    if (mysqli_query($connection, $updateQuery)) {
        mysqli_close($connection);

        // Write database configuration
        $dbConfigPath = '../../application/config/database.php';

        if (!file_exists($dbConfigPath)) {
            throw new Exception('Database config file not found.');
        }

        $dbConfigContent = file_get_contents($dbConfigPath);

        if ($dbConfigContent === false) {
            throw new Exception('Failed to read database config file');
        }

        // Properly escape values for PHP string
        $host_escaped = addslashes($host);
        $username_escaped = addslashes($username);
        $password_escaped = addslashes($password); // Handles empty password and special chars
        $database_escaped = addslashes($database);
        
        $dbConfigContent = str_replace('%HOSTNAME%', $host_escaped, $dbConfigContent);
        $dbConfigContent = str_replace('%USERNAME%', $username_escaped, $dbConfigContent);
        $dbConfigContent = str_replace('%PASSWORD%', $password_escaped, $dbConfigContent);
        $dbConfigContent = str_replace('%DATABASE%', $database_escaped, $dbConfigContent);

        if (file_put_contents($dbConfigPath, $dbConfigContent) === false) {
            throw new Exception('Failed to write database config file');
        }

        // Ensure license file exists (create default trial if missing)
        if (!file_exists(LICENSE_LOCK_FILE)) {
            if (!createDefaultTrialLicense($siteUrl)) {
                throw new Exception('Failed to create default license file');
            }
        }

        // Create install lock file
        $licenseInfo = '';
        if (file_exists(LICENSE_LOCK_FILE)) {
            if (!defined('NCS_BILLING')) {
                define('NCS_BILLING', true);
            }
            $licData = include(LICENSE_LOCK_FILE);
            $licenseInfo = "\nLicense Key: " . substr($licData['license_key'], 0, 10) . "****\n";
            $licenseInfo .= "License Type: " . $licData['license_type_name'] . "\n";
            $licenseInfo .= "Licensed To: " . $licData['name'] . "\n";
        }

        $lockContent = "Installation completed on: " . date('Y-m-d H:i:s') . "\n";
        $lockContent .= "Database: " . $database . "\n";
        $lockContent .= "Site URL: " . $siteUrl . "\n";
        $lockContent .= $licenseInfo;
        $lockContent .= "\nWARNING: Do not delete this file unless you want to re-install the application.\n";
        $lockContent .= "Re-installation will overwrite your existing database and cause data loss!\n";

        file_put_contents(INSTALLER_LOCK_FILE, $lockContent);

        return [
            'success' => true,
            'message' => 'Installation completed successfully!',
            'step' => 7,
            'progress' => 100,
            'redirect_url' => $siteUrl . '/login'
        ];
    } else {
        $error = mysqli_error($connection);
        mysqli_close($connection);
        return [
            'success' => false,
            'message' => 'Failed to finalize installation: ' . $error,
            'step' => 6,
            'progress' => 85
        ];
    }
}

/**
 * Show locked installation page
 */
function showLockedPage() {
    ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Installation Already Completed - Jasiri Dynamics System</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
            background: #f5f5f5;
            margin: 0;
            padding: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
        }
        .lock-container {
            background: white;
            border-radius: 16px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.15);
            max-width: 600px;
            width: 100%;
            overflow: hidden;
            animation: slideUp 0.4s ease-out;
        }
        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        .lock-header {
            background: #3498db;
            color: white;
            padding: 30px;
            text-align: center;
        }
        .lock-icon {
            font-size: 64px;
            margin-bottom: 15px;
        }
        .lock-header h1 {
            font-size: 28px;
            font-weight: 600;
            margin-bottom: 8px;
        }
        .lock-header p {
            font-size: 15px;
            opacity: 0.95;
        }
        .lock-body {
            padding: 30px;
        }
        .info-text {
            color: #555;
            font-size: 15px;
            line-height: 1.7;
            margin-bottom: 25px;
            text-align: center;
        }
        .warning-box {
            background: #fff3cd;
            border-left: 4px solid #ffc107;
            padding: 18px 20px;
            margin-bottom: 25px;
            border-radius: 8px;
        }
        .warning-box strong {
            display: flex;
            align-items: center;
            gap: 8px;
            color: #856404;
            margin-bottom: 12px;
            font-size: 16px;
        }
        .warning-box ul {
            color: #856404;
            margin: 0;
            padding-left: 25px;
            line-height: 1.8;
        }
        .warning-box li {
            margin-bottom: 8px;
        }
        .file-info {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin: 25px 0;
            border: 1px solid #e9ecef;
        }
        .file-info strong {
            display: block;
            color: #2c3e50;
            margin-bottom: 10px;
            font-size: 14px;
        }
        .file-path {
            background: #ffffff;
            padding: 12px 15px;
            border: 1px solid #dee2e6;
            border-radius: 6px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            color: #495057;
            margin-top: 10px;
            word-break: break-all;
            line-height: 1.6;
        }
    </style>
</head>
<body>
    <div class="lock-container">
        <div class="lock-header">
            <div class="lock-icon">
                <i class="fas fa-lock"></i>
            </div>
            <h1>Installation Already Completed</h1>
            <p>Your Jasiri Dynamics System has already been installed</p>
        </div>
        <div class="lock-body">
            <p class="info-text">The installation process has been completed and locked to prevent accidental re-installation.</p>
            
            <div class="warning-box">
                <strong><i class="fas fa-exclamation-triangle"></i> Important Security Notice</strong>
                <ul>
                    <li>Do not delete the lock file unless you intend to re-install</li>
                    <li>Re-installation will <strong>overwrite your existing database</strong></li>
                    <li>Always backup your data before re-installing</li>
                </ul>
            </div>

            <div class="file-info">
                <strong><i class="fas fa-file-alt"></i> To re-install:</strong>
                <p style="color: #666; font-size: 14px; margin-bottom: 10px;">Delete the lock file at the following location:</p>
                <div class="file-path"><?php echo realpath(INSTALLER_LOCK_FILE); ?></div>
            </div>
        </div>
    </div>
</body>
</html>
    <?php
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Jasiri Dynamics System - Installation</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .installer-container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            max-width: 900px;
            width: 100%;
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, #2c3e50, #34495e);
            color: white;
            padding: 30px;
            text-align: center;
        }
        .header h1 { font-size: 2.5rem; margin-bottom: 10px; font-weight: 300; }
        .header p { font-size: 1.1rem; opacity: 0.9; }
        .progress-container { padding: 30px; }
        .step-indicator {
            display: flex;
            justify-content: space-between;
            margin-bottom: 25px;
            position: relative;
        }
        .step-indicator::before {
            content: '';
            position: absolute;
            top: 20px;
            left: 0;
            right: 0;
            height: 2px;
            background: #e0e0e0;
            z-index: 1;
        }
        .step {
            display: flex;
            flex-direction: column;
            align-items: center;
            position: relative;
            z-index: 2;
            background: white;
            padding: 0 5px;
        }
        .step-number {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #e0e0e0;
            color: #666;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-bottom: 10px;
            transition: all 0.3s ease;
        }
        .step.active .step-number { background: #3498db; color: white; }
        .step.completed .step-number { background: #27ae60; color: white; }
        .step-label { font-size: 0.8rem; text-align: center; color: #666; font-weight: 500; }
        .step.active .step-label { color: #3498db; }
        .step.completed .step-label { color: #27ae60; }
        .progress-bar {
            width: 100%;
            height: 6px;
            background: #e0e0e0;
            border-radius: 3px;
            overflow: hidden;
            margin-bottom: 20px;
        }
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #3498db, #2ecc71);
            width: 0%;
            transition: width 0.5s ease;
        }
        .form-container { display: none; }
        .form-container.active { display: block; }
        .form-group { margin-bottom: 15px; }
        .form-group label {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 8px;
            font-weight: 600;
            color: #2c3e50;
            font-size: 0.95rem;
        }
        .form-group label i {
            color: #3498db;
            font-size: 0.9rem;
        }
        .form-group input, .form-group select {
            width: 100%;
            padding: 14px 16px;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            font-size: 0.95rem;
            transition: all 0.3s ease;
            background: #fff;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        .form-group input:focus, .form-group select:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
            transform: translateY(-1px);
        }
        .form-group input:hover, .form-group select:hover {
            border-color: #bdc3c7;
        }
        .form-group small { 
            display: flex;
            align-items: center;
            gap: 6px;
            margin-top: 8px; 
            color: #7f8c8d; 
            font-size: 0.85rem; 
            font-style: italic;
        }
        .form-group small i {
            color: #95a5a6;
            font-size: 0.8rem;
        }
        .btn {
            background: linear-gradient(135deg, #3498db, #2980b9);
            color: white;
            border: none;
            padding: 14px 30px;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 100%;
        }
        .btn:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(52, 152, 219, 0.4); }
        .btn:disabled { background: #bdc3c7; cursor: not-allowed; transform: none; box-shadow: none; }
        .btn-success { background: linear-gradient(135deg, #27ae60, #2ecc71); }
        .btn-success:hover { box-shadow: 0 5px 15px rgba(39, 174, 96, 0.4); }
        .status-message {
            text-align: center;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 15px;
            font-weight: 500;
            font-size: 0.95rem;
            display: none;
        }
        .status-message.show { display: block; }
        .status-message.success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .status-message.error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .status-message.info { background: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb; }
        .status-message.warning { background: #fff3cd; color: #856404; border: 1px solid #ffc107; }
        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 10px;
        }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
        .license-info-box {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            color: white;
        }
        .license-info-box h4 { margin-bottom: 15px; font-size: 1.1rem; }
        .license-info-box .info-row {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid rgba(255,255,255,0.2);
        }
        .license-info-box .info-row:last-child { border-bottom: none; }
        .license-info-box .info-label { opacity: 0.8; }
        .license-info-box .info-value { font-weight: 600; }
        .success-screen { text-align: center; padding: 40px; }
        .success-icon { font-size: 4rem; color: #27ae60; margin-bottom: 20px; }
        .success-screen h2 { color: #2c3e50; margin-bottom: 20px; }
        .success-screen p { color: #666; margin-bottom: 30px; }
        .credentials-box {
            background: #f8f9fa;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            padding: 20px;
            margin: 20px 0;
            text-align: left;
        }
        .credentials-box h4 { color: #2c3e50; margin-bottom: 15px; text-align: center; }
        .credentials-box .cred-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        .credentials-box code {
            background: #e9ecef;
            padding: 5px 10px;
            border-radius: 5px;
            font-size: 1.1rem;
        }
        .section-title {
            font-size: 1.5rem;
            color: #2c3e50;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 2px solid #ecf0f1;
            display: flex;
            align-items: center;
            gap: 12px;
            font-weight: 600;
        }
        .section-title i { 
            color: #3498db; 
            font-size: 1.3rem;
        }
    </style>
</head>
<body>
    <div class="installer-container">
        <div class="header">
            <h1><i class="fas fa-cube"></i> Jasiri Dynamics System</h1>
            <p>Complete POS & Inventory Management Solution</p>
        </div>

        <div class="progress-container">
            <!-- Step Indicator -->
            <div class="step-indicator">
                <div class="step active" id="step-1">
                    <div class="step-number">1</div>
                    <div class="step-label">License</div>
                </div>
                <div class="step" id="step-2">
                    <div class="step-number">2</div>
                    <div class="step-label">Database</div>
                </div>
                <div class="step" id="step-3">
                    <div class="step-number">3</div>
                    <div class="step-label">Create DB</div>
                </div>
                <div class="step" id="step-4">
                    <div class="step-number">4</div>
                    <div class="step-label">Install</div>
                </div>
                <div class="step" id="step-5">
                    <div class="step-number">5</div>
                    <div class="step-label">Configure</div>
                </div>
                <div class="step" id="step-6">
                    <div class="step-number">6</div>
                    <div class="step-label">Complete</div>
                </div>
            </div>

            <!-- Progress Bar -->
            <div class="progress-bar">
                <div class="progress-fill" id="progress-fill"></div>
            </div>

            <!-- Status Message -->
            <div id="status-message" class="status-message">
                <span id="status-text"></span>
            </div>

            <!-- Step 1: License Verification -->
            <div class="form-container active" id="form-step-1">
                <h3 class="section-title"><i class="fas fa-key"></i> License Verification</h3>
                <div class="status-message info show" style="margin-bottom: 20px;">
                    <i class="fas fa-info-circle"></i> A valid license is required to install Jasiri Dynamics System.
                    Enter the license details exactly as provided when you purchased the System. For Support Whatsapp/Call +254799-075-857 or +254707-733-580
                </div>

                <form id="license-form">
                    <div class="form-group">
                        <label for="license_key"><i class="fas fa-key"></i> License Key *</label>
                        <input type="text" id="license_key" name="license_key" placeholder="JASD-XXXX-XXXX-XXXX-XXXX" required>
                        <small>Enter the license key you received after purchase</small>
                    </div>
                    <div class="form-group">
                        <label for="license_name"><i class="fas fa-user"></i> Customer Name *</label>
                        <input type="text" id="license_name" name="license_name" placeholder="John Doe or Company Name" required>
                        <small>Must match the name used during purchase</small>
                    </div>
                    <div class="form-group">
                        <label for="license_email"><i class="fas fa-envelope"></i> Customer Email *</label>
                        <input type="email" id="license_email" name="license_email" placeholder="your@email.com" required>
                        <small>Must match the email used during purchase</small>
                    </div>
                    <button type="submit" class="btn" id="verify-license-btn">
                        <i class="fas fa-shield-alt"></i> Verify License
                    </button>
                </form>
            </div>

            <!-- Step 2: Database Configuration -->
            <div class="form-container" id="form-step-2">
                <div id="license-info-display" class="license-info-box" style="display: none;">
                    <h4><i class="fas fa-check-circle"></i> License Verified</h4>
                    <div class="info-row">
                        <span class="info-label">Licensed To:</span>
                        <span class="info-value" id="display-name">-</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">License Type:</span>
                        <span class="info-value" id="display-type">-</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Expires:</span>
                        <span class="info-value" id="display-expiry">-</span>
                    </div>
                </div>

                <h3 class="section-title"><i class="fas fa-database"></i> Database Configuration</h3>
                <form id="install-form">
                    <div class="form-group">
                        <label for="hostname"><i class="fas fa-server"></i> Database Host *</label>
                        <input type="text" id="hostname" name="hostname" value="localhost" placeholder="localhost or 127.0.0.1" required>
                        <small><i class="fas fa-info-circle"></i> Usually "localhost" for local installations</small>
                    </div>
                    <div class="form-group">
                        <label for="username"><i class="fas fa-user"></i> Database Username *</label>
                        <input type="text" id="username" name="username" value="root" placeholder="root or your MySQL username" required>
                        <small><i class="fas fa-info-circle"></i> Your MySQL database username</small>
                    </div>
                    <div class="form-group">
                        <label for="password"><i class="fas fa-lock"></i> Database Password</label>
                        <input type="password" id="password" name="password" placeholder="Leave empty if no password">
                        <small><i class="fas fa-info-circle"></i> Leave empty if your MySQL has no password</small>
                    </div>
                    <div class="form-group">
                        <label for="database"><i class="fas fa-database"></i> Database Name *</label>
                        <input type="text" id="database" name="database" placeholder="e.g jdsbilling" required>
                        <small><i class="fas fa-info-circle"></i> Create this database in your MySQL if it doesn't exist</small>
                    </div>
                    <div class="form-group">
                        <label for="site_url"><i class="fas fa-link"></i> Site URL *</label>
                        <input type="url" id="site_url" name="site_url" value="<?php echo $urlWb; ?>" required readonly style="background-color: #f8f9fa; cursor: not-allowed;">
                        <small><i class="fas fa-info-circle"></i> Auto-detected from your domain (locked to license)</small>
                    </div>
                    <button type="submit" class="btn" id="install-btn">
                        <i class="fas fa-play"></i> Start Installation
                    </button>
                </form>
            </div>

            <!-- Success Screen -->
            <div class="form-container" id="success-screen">
                <div class="success-screen">
                    <div class="success-icon"><i class="fas fa-check-circle"></i></div>
                    <h2>Installation Complete!</h2>
                    <p>Jasiri Dynamics System has been successfully installed and activated.</p>

                    <div class="credentials-box">
                        <h4><i class="fas fa-key"></i> Default Login Credentials</h4>
                        <div class="cred-row">
                            <strong>Email:</strong>
                            <code>admin@example.com</code>
                        </div>
                        <div class="cred-row">
                            <strong>Password:</strong>
                            <code>123456</code>
                        </div>
                        <div style="text-align: center; margin-top: 15px; color: #6c757d; font-size: 0.9rem;">
                            <i class="fas fa-info-circle"></i> Please change these credentials after your first login
                        </div>
                    </div>

                    <div style="background: #d1ecf1; border: 2px solid #0c5460; border-radius: 10px; padding: 15px; margin: 20px 0;">
                        <h5 style="color: #0c5460; margin-bottom: 10px; text-align: center;">
                            <i class="fas fa-shield-alt"></i> Installation Protected
                        </h5>
                        <p style="color: #0c5460; font-size: 0.9rem; margin: 0; text-align: center;">
                            Your installation and license are now locked to this system.<br>
                            Do not delete the lock files to maintain license validity.
                        </p>
                    </div>

                    <button class="btn btn-success" id="go-to-login">
                        <i class="fas fa-sign-in-alt"></i> Go to Login Page
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentStep = 1;
        let installationData = {};
        let licenseVerified = false;

        // License form submission
        document.getElementById('license-form').addEventListener('submit', function(e) {
            e.preventDefault();
            verifyLicense();
        });

        // Install form submission
        document.getElementById('install-form').addEventListener('submit', function(e) {
            e.preventDefault();
            if (!licenseVerified) {
                showStatus('Please verify your license first.', 'error');
                return;
            }
            startInstallation();
        });

        // Go to login button
        document.getElementById('go-to-login').addEventListener('click', function() {
            window.location.href = installationData.site_url + '/login';
        });

        async function verifyLicense() {
            const licenseKey = document.getElementById('license_key').value.trim();
            const licenseName = document.getElementById('license_name').value.trim();
            const licenseEmail = document.getElementById('license_email').value.trim();

            if (!licenseKey || !licenseName || !licenseEmail) {
                showStatus('All fields are required.', 'error');
                return;
            }

            const btn = document.getElementById('verify-license-btn');
            btn.disabled = true;
            btn.innerHTML = '<span class="loading-spinner"></span>Verifying License...';

            showStatus('Connecting to license server...', 'info');

            try {
                const response = await fetch('', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: new URLSearchParams({
                        action: 'verify_license',
                        license_key: licenseKey,
                        license_name: licenseName,
                        license_email: licenseEmail
                    })
                });

                const result = await response.json();

                if (result.success) {
                    licenseVerified = true;
                    showStatus(result.message, 'success');
                    updateStep(result.step, result.progress);

                    // Show license info
                    if (result.license_info) {
                        document.getElementById('display-name').textContent = result.license_info.name;
                        document.getElementById('display-type').textContent = result.license_info.type;
                        document.getElementById('display-expiry').textContent = result.license_info.expiry;
                        document.getElementById('license-info-display').style.display = 'block';
                    }

                    // Switch to database form
                    setTimeout(() => {
                        document.getElementById('form-step-1').classList.remove('active');
                        document.getElementById('form-step-2').classList.add('active');
                    }, 1500);
                } else {
                    showStatus(result.message, 'error');
                    btn.disabled = false;
                    btn.innerHTML = '<i class="fas fa-shield-alt"></i> Verify License';
                }
            } catch (error) {
                showStatus('Connection error. Please check your internet and try again.', 'error');
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-shield-alt"></i> Verify License';
            }
        }

        async function startInstallation() {
            const formData = new FormData(document.getElementById('install-form'));
            installationData = Object.fromEntries(formData.entries());

            const btn = document.getElementById('install-btn');
            btn.disabled = true;
            btn.innerHTML = '<span class="loading-spinner"></span>Installing...';

            try {
                await runInstallationStep('validate_database', 'Validating database connection...');
                await runInstallationStep('create_database', 'Creating database...');
                await runInstallationStep('install_tables', 'Installing database tables (this may take a while)...');
                await runInstallationStep('create_admin', 'Configuring admin user...');
                await runInstallationStep('finalize', 'Finalizing installation...');

                showSuccessScreen();
            } catch (error) {
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-play"></i> Retry Installation';
            }
        }

        async function runInstallationStep(action, message) {
            showStatus(message, 'info');

            const response = await fetch('', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    action: action,
                    ...installationData
                })
            });

            const result = await response.json();

            if (result.success) {
                updateStep(result.step, result.progress);
                showStatus(result.message, 'success');
                await new Promise(resolve => setTimeout(resolve, 1500));
            } else {
                showStatus(result.message, 'error');
                throw new Error(result.message);
            }
        }

        function updateStep(step, progress) {
            document.getElementById('progress-fill').style.width = progress + '%';

            for (let i = 1; i <= 6; i++) {
                const stepElement = document.getElementById(`step-${i}`);
                if (i < step) {
                    stepElement.classList.add('completed');
                    stepElement.classList.remove('active');
                } else if (i === step) {
                    stepElement.classList.add('active');
                    stepElement.classList.remove('completed');
                } else {
                    stepElement.classList.remove('active', 'completed');
                }
            }
        }

        function showStatus(message, type) {
            const statusElement = document.getElementById('status-message');
            const statusText = document.getElementById('status-text');

            statusElement.className = `status-message ${type} show`;
            statusText.innerHTML = message;
        }

        function showSuccessScreen() {
            document.getElementById('form-step-2').classList.remove('active');
            document.getElementById('success-screen').classList.add('active');
        }
    </script>
</body>
</html>
