<?php
/**
 * Student Management System - Installation Script
 * Run this file once to set up the database and initial configuration
 */

// Check if already installed
if (file_exists('config/installed.lock')) {
    die('System is already installed. Delete config/installed.lock to reinstall.');
}

$error_message = '';
$success_message = '';

if ($_POST) {
    $host = $_POST['host'] ?? 'localhost';
    $dbname = $_POST['dbname'] ?? 'student_management';
    $username = $_POST['username'] ?? 'root';
    $password = $_POST['password'] ?? '';
    $admin_username = $_POST['admin_username'] ?? 'admin';
    $admin_password = $_POST['admin_password'] ?? 'admin123';
    $admin_email = $_POST['admin_email'] ?? 'admin@school.com';
    $admin_name = $_POST['admin_name'] ?? 'System Administrator';

    try {
        // Test database connection
        $pdo = new PDO("mysql:host=$host", $username, $password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        // Create database if it doesn't exist
        $pdo->exec("CREATE DATABASE IF NOT EXISTS `$dbname`");
        $pdo->exec("USE `$dbname`");

        // Read and execute schema
        $schema = file_get_contents('database/schema.sql');
        $statements = explode(';', $schema);
        
        foreach ($statements as $statement) {
            $statement = trim($statement);
            if (!empty($statement)) {
                $pdo->exec($statement);
            }
        }

        // Update admin credentials
        $hashed_password = password_hash($admin_password, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("UPDATE admins SET username = ?, password = ?, email = ?, full_name = ? WHERE id = 1");
        $stmt->execute([$admin_username, $hashed_password, $admin_email, $admin_name]);

        // Update database configuration
        $config_content = "<?php
class Database {
    private \$host = \"$host\";
    private \$db_name = \"$dbname\";
    private \$username = \"$username\";
    private \$password = \"$password\";
    public \$conn;

    public function getConnection() {
        \$this->conn = null;
        try {
            \$this->conn = new PDO(\"mysql:host=\" . \$this->host . \";dbname=\" . \$this->db_name, \$this->username, \$this->password);
            \$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            \$this->conn->exec(\"set names utf8\");
        } catch(PDOException \$exception) {
            echo \"Connection error: \" . \$exception->getMessage();
        }
        return \$this->conn;
    }
}
?>";

        file_put_contents('config/database.php', $config_content);

        // Create installation lock file
        file_put_contents('config/installed.lock', date('Y-m-d H:i:s'));

        $success_message = 'Installation completed successfully! You can now <a href="login.php">login to the system</a>.';
        
    } catch (PDOException $e) {
        $error_message = 'Database error: ' . $e->getMessage();
    } catch (Exception $e) {
        $error_message = 'Installation error: ' . $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Installation - Student Management System</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
        }
        .install-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        .install-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 20px 20px 0 0;
            padding: 2rem;
            text-align: center;
        }
        .form-control {
            border-radius: 10px;
            border: 2px solid #e9ecef;
            padding: 12px 15px;
            transition: all 0.3s ease;
        }
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        .btn-install {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 10px;
            padding: 12px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        .btn-install:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8 col-lg-6">
                <div class="card install-card">
                    <div class="install-header">
                        <i class="fas fa-graduation-cap fa-3x mb-3"></i>
                        <h3>Student Management System</h3>
                        <p class="mb-0">Installation Wizard</p>
                    </div>
                    <div class="card-body p-4">
                        <?php if ($error_message): ?>
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                <?php echo $error_message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>

                        <?php if ($success_message): ?>
                            <div class="alert alert-success alert-dismissible fade show" role="alert">
                                <i class="fas fa-check-circle me-2"></i>
                                <?php echo $success_message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>

                        <?php if (!$success_message): ?>
                        <form method="POST" action="">
                            <h5 class="mb-3">Database Configuration</h5>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="host" class="form-label">Database Host</label>
                                    <input type="text" class="form-control" id="host" name="host" value="localhost" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="dbname" class="form-label">Database Name</label>
                                    <input type="text" class="form-control" id="dbname" name="dbname" value="student_management" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="username" class="form-label">Database Username</label>
                                    <input type="text" class="form-control" id="username" name="username" value="root" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="password" class="form-label">Database Password</label>
                                    <input type="password" class="form-control" id="password" name="password">
                                </div>
                            </div>

                            <hr class="my-4">

                            <h5 class="mb-3">Admin Account</h5>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="admin_username" class="form-label">Admin Username</label>
                                    <input type="text" class="form-control" id="admin_username" name="admin_username" value="admin" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="admin_password" class="form-label">Admin Password</label>
                                    <input type="password" class="form-control" id="admin_password" name="admin_password" value="admin123" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="admin_email" class="form-label">Admin Email</label>
                                    <input type="email" class="form-control" id="admin_email" name="admin_email" value="admin@school.com" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="admin_name" class="form-label">Admin Full Name</label>
                                    <input type="text" class="form-control" id="admin_name" name="admin_name" value="System Administrator" required>
                                </div>
                            </div>

                            <div class="alert alert-info">
                                <i class="fas fa-info-circle me-2"></i>
                                <strong>Note:</strong> Make sure your MySQL server is running and the database credentials are correct.
                            </div>

                            <button type="submit" class="btn btn-primary btn-install w-100">
                                <i class="fas fa-download me-2"></i>Install System
                            </button>
                        </form>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
