<?php
// Start session if not already started
session_start();
require 'db_connection.php';

// Initialize variables
$error_message = '';
$success_message = '';

// Handle registration form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate inputs (basic example)
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];

    // Check if passwords match
    if ($password !== $confirm_password) {
        $error_message = "Passwords do not match";
    } else {
        // Check if username or email already exists
        $check_query = "SELECT * FROM users WHERE username = ? OR email = ?";
        $stmt = $conn->prepare($check_query);
        $stmt->bind_param("ss", $username, $email);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $error_message = "Username or email already exists";
        } else {
            // Hash the password
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);

            // Prepare and bind SQL statement
            $sql = "INSERT INTO users (username, email, password, role) VALUES (?, ?, ?, 'admin')";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("sss", $username, $email, $hashed_password);

            // Execute the statement
            if ($stmt->execute()) {
                $success_message = "Admin account created successfully!";
                // Reset form fields
                $username = $email = '';
            } else {
                // Error inserting record
                $error_message = "Error: " . $sql . "<br>" . $conn->error;
            }
        }
        $stmt->close();
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register Admin - School Management System</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #3a57e8;
            --secondary: #6c757d;
            --success: #1cbb8c;
            --info: #17a2b8;
            --warning: #f5b759;
            --danger: #fc5b69;
            --light: #f8f9fa;
            --dark: #343a40;
        }
        
        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .register-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            width: 400px;
            max-width: 90%;
        }
        
        .register-header {
            background: linear-gradient(135deg, var(--primary) 0%, #2039c5 100%);
            color: white;
            padding: 25px;
            text-align: center;
        }
        
        .register-header h2 {
            margin-bottom: 5px;
            font-weight: 700;
        }
        
        .register-header p {
            opacity: 0.9;
            margin-bottom: 0;
        }
        
        .register-form {
            padding: 25px;
        }
        
        .form-control:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 0.25rem rgba(58, 87, 232, 0.25);
        }
        
        .btn-register {
            background: var(--primary);
            border: none;
            color: white;
            padding: 12px;
            width: 100%;
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .btn-register:hover {
            background: #2039c5;
            color: white;
        }
        
        .password-strength {
            height: 5px;
            margin-top: 5px;
            border-radius: 5px;
            background: #e9ecef;
        }
        
        .password-strength-bar {
            height: 100%;
            border-radius: 5px;
            width: 0%;
            transition: width 0.3s;
        }
        
        .password-requirements {
            font-size: 0.8rem;
            color: var(--secondary);
            margin-top: 5px;
        }
        
        .login-link {
            text-align: center;
            margin-top: 20px;
            font-size: 0.9rem;
        }
        
        .input-icon {
            position: relative;
        }
        
        .input-icon i {
            position: absolute;
            left: 15px;
            top: 12px;
            color: var(--secondary);
        }
        
        .input-icon input {
            padding-left: 40px;
        }
    </style>
</head>
<body>
    <div class="register-container">
        <div class="register-header">
            <h2><i class="fas fa-user-shield me-2"></i>Admin Registration</h2>
            <p>Create a new administrator account</p>
        </div>
        
        <div class="register-form">
            <!-- Display messages -->
            <?php if (!empty($error_message)): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-circle me-2"></i> <?php echo $error_message; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>
            
            <?php if (!empty($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" aria-label="Close"></button>
                </div>
            <?php endif; ?>
            
            <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST" id="registrationForm">
                <div class="mb-3 input-icon">
                    <i class="fas fa-user"></i>
                    <input type="text" class="form-control" id="username" name="username" 
                           value="<?php echo isset($username) ? htmlspecialchars($username) : ''; ?>" 
                           placeholder="Username" required>
                </div>
                
                <div class="mb-3 input-icon">
                    <i class="fas fa-envelope"></i>
                    <input type="email" class="form-control" id="email" name="email" 
                           value="<?php echo isset($email) ? htmlspecialchars($email) : ''; ?>" 
                           placeholder="Email Address" required>
                </div>
                
                <div class="mb-3 input-icon">
                    <i class="fas fa-lock"></i>
                    <input type="password" class="form-control" id="password" name="password" 
                           placeholder="Password" required>
                    <div class="password-strength">
                        <div class="password-strength-bar" id="passwordStrengthBar"></div>
                    </div>
                    <div class="password-requirements">
                        Must be at least 8 characters with letters and numbers
                    </div>
                </div>
                
                <div class="mb-3 input-icon">
                    <i class="fas fa-lock"></i>
                    <input type="password" class="form-control" id="confirm_password" name="confirm_password" 
                           placeholder="Confirm Password" required>
                </div>
                
                <button type="submit" class="btn btn-register">
                    <i class="fas fa-user-plus me-2"></i> Register Admin
                </button>
            </form>
            
            <div class="login-link">
                <p>Already have an account? <a href="login.php">Login here</a></p>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const passwordInput = document.getElementById('password');
            const strengthBar = document.getElementById('passwordStrengthBar');
            const confirmPasswordInput = document.getElementById('confirm_password');
            
            // Password strength indicator
            passwordInput.addEventListener('input', function() {
                const password = passwordInput.value;
                let strength = 0;
                
                // Check password strength
                if (password.length >= 8) strength += 25;
                if (/[A-Z]/.test(password)) strength += 25;
                if (/[0-9]/.test(password)) strength += 25;
                if (/[^A-Za-z0-9]/.test(password)) strength += 25;
                
                // Update strength bar
                strengthBar.style.width = strength + '%';
                
                // Update color based on strength
                if (strength < 50) {
                    strengthBar.style.backgroundColor = '#dc3545'; // Red
                } else if (strength < 75) {
                    strengthBar.style.backgroundColor = '#fd7e14'; // Orange
                } else if (strength < 100) {
                    strengthBar.style.backgroundColor = '#ffc107'; // Yellow
                } else {
                    strengthBar.style.backgroundColor = '#198754'; // Green
                }
            });
            
            // Form validation
            const form = document.getElementById('registrationForm');
            form.addEventListener('submit', function(event) {
                let isValid = true;
                
                // Check if passwords match
                if (passwordInput.value !== confirmPasswordInput.value) {
                    isValid = false;
                    alert('Passwords do not match');
                    event.preventDefault();
                }
                
                // Check password strength
                if (passwordInput.value.length < 8) {
                    isValid = false;
                    alert('Password must be at least 8 characters long');
                    event.preventDefault();
                }
                
                return isValid;
            });
        });
    </script>
</body>
</html>