<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Billing System Setup</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/cosmo/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <div class="col-md-6 col-md-offset-3">
            <h2>Billing System - Quick Setup</h2>
            <hr>
            
            <?php
            if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                try {
                    // First, create the database if it doesn't exist
                    $conn = new mysqli($_POST['hostname'], $_POST['username'], $_POST['password']);
                    if ($conn->connect_error) {
                        throw new Exception("Connection failed: " . $conn->connect_error);
                    }
                    
                    $database_name = $_POST['database'];
                    $sql = "CREATE DATABASE IF NOT EXISTS `{$database_name}` CHARACTER SET utf8 COLLATE utf8_general_ci";
                    if (!$conn->query($sql)) {
                        throw new Exception("Error creating database: " . $conn->error);
                    }
                    $conn->close();
                    
                    echo '<div class="alert alert-info">Database created/verified successfully.</div>';
                    
                    // Change to the setup/install directory for proper file paths
                    $original_dir = getcwd();
                    chdir('setup/install');
                    
                    // Include required files
                    require_once('taskCoreClass.php');
                    require_once('includes/databaseLibrary.php');
                    
                    $core = new Core();
                    $database = new Database();
                
                // Prepare data with dummy values for required fields
                $data = array(
                    'hostname' => $_POST['hostname'],
                    'username' => $_POST['username'],
                    'password' => $_POST['password'],
                    'database' => $_POST['database'],
                    'url' => $_POST['url'],
                    'purchase_code' => 'local-dev-' . time(), // Dummy purchase code
                    'envato_username' => 'local-dev', // Dummy username
                    'email' => $_POST['email'] ?: 'admin@localhost.com'
                );
                
                // Check if database exists
                if ($database->check_database_exist_or_not($data)) {
                    // Create tables
                    if ($database->create_tables($data)) {
                        // Write config
                        if ($core->write_config($data)) {
                            echo '<div class="alert alert-success">
                                    <h4>Installation Successful!</h4>
                                    <p>Your billing system has been installed successfully.</p>
                                    <p><strong>Login Details:</strong></p>
                                    <p>Username: <code>admin@example.com</code></p>
                                    <p>Password: <code>123456</code></p>
                                    <p><a href="index.php" class="btn btn-primary">Go to Application</a></p>
                                  </div>';
                            
                            // Update index.php to set environment to development
                            chdir($original_dir); // Go back to root directory
                            $index_content = file_get_contents('index.php');
                            $index_content = str_replace("define('ENVIRONMENT', 'SETUP');", "define('ENVIRONMENT', 'development');", $index_content);
                            file_put_contents('index.php', $index_content);
                            
                        } else {
                            chdir($original_dir); // Go back to root directory
                            echo '<div class="alert alert-danger">Failed to write configuration file.</div>';
                        }
                    } else {
                        chdir($original_dir); // Go back to root directory
                        echo '<div class="alert alert-danger">Failed to create database tables.</div>';
                    }
                } else {
                    chdir($original_dir); // Go back to root directory
                    echo '<div class="alert alert-danger">Database does not exist. Please create the database first.</div>';
                }
                
                } catch (Exception $e) {
                    if (isset($original_dir)) {
                        chdir($original_dir); // Go back to root directory
                    }
                    echo '<div class="alert alert-danger">Error: ' . $e->getMessage() . '</div>';
                }
            } else {
            ?>
            
            <form method="POST">
                <div class="form-group">
                    <label>Database Hostname</label>
                    <input type="text" name="hostname" value="localhost" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label>Database Username</label>
                    <input type="text" name="username" value="root" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label>Database Password</label>
                    <input type="password" name="password" value="" class="form-control">
                </div>
                
                <div class="form-group">
                    <label>Database Name</label>
                    <input type="text" name="database" value="billing_pos" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label>Application URL</label>
                    <input type="text" name="url" value="<?php echo 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/'; ?>" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label>Email (Optional)</label>
                    <input type="email" name="email" value="admin@localhost.com" class="form-control">
                </div>
                
                <button type="submit" class="btn btn-primary btn-lg btn-block">Install Application</button>
            </form>
            
            <div class="alert alert-info">
                <strong>Note:</strong> This installer bypasses the Envato license verification for local development.
                Make sure you have already created the database "billing_pos" before proceeding.
            </div>
            
            <?php } ?>
        </div>
    </div>
</body>
</html>
