<?php
session_start();
require_once 'config/database.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

$database = new Database();
$conn = $database->getConnection();

// Get admin info
$admin_id = $_SESSION['admin_id'];
$stmt = $conn->prepare("SELECT * FROM admins WHERE id = ?");
$stmt->execute([$admin_id]);
$current_admin = $stmt->fetch();

// Handle form submission
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    $role = $_POST['role'];
    $status = $_POST['status'];
    
    // Validate inputs
    $errors = [];
    
    if (empty($username)) {
        $errors[] = 'Username is required.';
    } elseif (strlen($username) < 3) {
        $errors[] = 'Username must be at least 3 characters long.';
    }
    
    if (empty($email)) {
        $errors[] = 'Email is required.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Please enter a valid email address.';
    }
    
    if (empty($password)) {
        $errors[] = 'Password is required.';
    } elseif (strlen($password) < 6) {
        $errors[] = 'Password must be at least 6 characters long.';
    }
    
    if ($password !== $confirm_password) {
        $errors[] = 'Passwords do not match.';
    }
    
    if (empty($role)) {
        $errors[] = 'Role is required.';
    }
    
    if (empty($status)) {
        $errors[] = 'Status is required.';
    }
    
    if (empty($errors)) {
        // Check if username or email already exists
        $stmt = $conn->prepare("SELECT id FROM admins WHERE username = ? OR email = ?");
        $stmt->execute([$username, $email]);
        if ($stmt->fetch()) {
            $errors[] = 'Username or email already exists.';
        } else {
            // Create new admin
            $password_hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("INSERT INTO admins (username, email, password_hash, role, status) VALUES (?, ?, ?, ?, ?)");
            if ($stmt->execute([$username, $email, $password_hash, $role, $status])) {
                $message = 'Administrator created successfully!';
                $message_type = 'success';
                
                // Clear form data
                $_POST = [];
            } else {
                $errors[] = 'Failed to create administrator. Please try again.';
            }
        }
    }
    
    if (!empty($errors)) {
        $message = implode('<br>', $errors);
        $message_type = 'error';
    }
}

$database->closeConnection();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TrustBeam Credit - Create Administrator</title>
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .form-container {
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            max-width: 600px;
            margin: 0 auto;
        }
        
        .form-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            text-align: center;
        }
        
        .form-header h3 {
            margin: 0;
            font-size: 24px;
        }
        
        .form-header p {
            margin: 5px 0 0 0;
            opacity: 0.9;
        }
        
        .form-content {
            padding: 30px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }
        
        .form-group input,
        .form-group select {
            width: 100%;
            padding: 12px;
            border: 2px solid #e1e5e9;
            border-radius: 6px;
            font-size: 14px;
            transition: border-color 0.3s ease;
        }
        
        .form-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .form-group small {
            display: block;
            margin-top: 5px;
            color: #666;
            font-size: 12px;
        }
        
        .password-requirements {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 4px;
            padding: 10px;
            margin-top: 5px;
            font-size: 12px;
            color: #666;
        }
        
        .btn-group {
            display: flex;
            gap: 15px;
            justify-content: center;
            margin-top: 30px;
        }
        
        .btn {
            padding: 12px 30px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            text-align: center;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }
        
        .btn-secondary {
            background-color: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background-color: #5a6268;
        }
        
        .alert {
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 6px;
            border-left: 4px solid;
        }
        
        .alert-success {
            background-color: #d4edda;
            color: #155724;
            border-left-color: #28a745;
        }
        
        .alert-error {
            background-color: #f8d7da;
            color: #721c24;
            border-left-color: #dc3545;
        }
        
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        
        @media (max-width: 768px) {
            .form-row {
                grid-template-columns: 1fr;
            }
            
            .btn-group {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="admin-container">
        <!-- Header -->
        <header class="admin-header">
            <div class="header-left">
                <h1 class="logo">TrustBeam Credit</h1>
                <button class="menu-toggle" id="menuToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="search-bar">
                    <i class="fas fa-search"></i>
                    <input type="text" placeholder="Search...">
                </div>
            </div>
            <div class="header-right">
                <div class="admin-profile">
                    <span>Welcome, <?php echo htmlspecialchars($current_admin['username']); ?></span>
                    <div class="profile-dropdown">
                        <i class="fas fa-user"></i>
                        <div class="dropdown-content">
                            <a href="profile.php">Profile</a>
                            <a href="logout.php">Logout</a>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <!-- Sidebar -->
        <aside class="admin-sidebar" id="sidebar">
            <div class="sidebar-header">
                <h3>Admin Manager</h3>
                <p>Admin</p>
            </div>
            <nav class="sidebar-nav">
                <ul>
                    <li>
                        <a href="index.php">
                            <i class="fas fa-home"></i>
                            <span>Dashboard</span>
                        </a>
                    </li>
                    <li>
                        <a href="users.php">
                            <i class="fas fa-users"></i>
                            <span>Manage Users</span>
                        </a>
                    </li>
                    <li>
                        <a href="create-user.php">
                            <i class="fas fa-user-plus"></i>
                            <span>Create New User</span>
                        </a>
                    </li>
                    <li>
                        <a href="applications.php">
                            <i class="fas fa-user-friends"></i>
                            <span>New User Application(s)</span>
                        </a>
                    </li>
                    <li>
                        <a href="transactions.php">
                            <i class="fas fa-exchange-alt"></i>
                            <span>Transfer Transactions</span>
                        </a>
                    </li>
                    <li>
                        <a href="deposits.php">
                            <i class="fas fa-arrow-down"></i>
                            <span>Users Deposits</span>
                        </a>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-cog"></i>
                            <span>Loan Applications</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="loans.php">View All</a></li>
                            <li><a href="loans.php?status=pending">Pending</a></li>
                            <li><a href="loans.php?status=approved">Approved</a></li>
                        </ul>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-credit-card"></i>
                            <span>Virtual Cards</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="cards.php">Manage Cards</a></li>
                            <li><a href="cards.php?status=active">Active</a></li>
                        </ul>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-file-invoice-dollar"></i>
                            <span>IRS Refunds</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="refunds.php">View All</a></li>
                            <li><a href="refunds.php?status=pending">Pending</a></li>
                        </ul>
                    </li>
                    <li>
                        <a href="email.php">
                            <i class="fas fa-envelope"></i>
                            <span>Email Services</span>
                        </a>
                    </li>
                    <li class="has-submenu active">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-user-shield"></i>
                            <span>Administrator(s)</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="admins.php">View All</a></li>
                            <li><a href="create-admin.php" class="active">Add New</a></li>
                        </ul>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-cog"></i>
                            <span>Settings</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="settings.php">General</a></li>
                            <li><a href="security.php">Security</a></li>
                        </ul>
                    </li>
                </ul>
            </nav>
        </aside>

        <!-- Main Content -->
        <main class="admin-main">
            <div class="dashboard-header">
                <h2>Create New Administrator</h2>
                <p>Add a new administrator to the system</p>
            </div>

            <!-- Messages -->
            <?php if ($message): ?>
                <div class="alert alert-<?php echo $message_type; ?>">
                    <?php echo $message; ?>
                </div>
            <?php endif; ?>

            <!-- Create Administrator Form -->
            <div class="form-container">
                <div class="form-header">
                    <h3><i class="fas fa-user-plus"></i> Administrator Information</h3>
                    <p>Fill in the details to create a new administrator account</p>
                </div>
                
                <div class="form-content">
                    <form method="POST" action="">
                        <div class="form-row">
                            <div class="form-group">
                                <label for="username">
                                    <i class="fas fa-user"></i> Username *
                                </label>
                                <input type="text" 
                                       id="username" 
                                       name="username" 
                                       value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>"
                                       required>
                                <small>Choose a unique username (minimum 3 characters)</small>
                            </div>
                            
                            <div class="form-group">
                                <label for="email">
                                    <i class="fas fa-envelope"></i> Email Address *
                                </label>
                                <input type="email" 
                                       id="email" 
                                       name="email" 
                                       value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>"
                                       required>
                                <small>This will be used for login and notifications</small>
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label for="password">
                                    <i class="fas fa-lock"></i> Password *
                                </label>
                                <input type="password" 
                                       id="password" 
                                       name="password" 
                                       required>
                                <div class="password-requirements">
                                    <strong>Password Requirements:</strong><br>
                                    • At least 6 characters long<br>
                                    • Use a combination of letters and numbers for security
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label for="confirm_password">
                                    <i class="fas fa-lock"></i> Confirm Password *
                                </label>
                                <input type="password" 
                                       id="confirm_password" 
                                       name="confirm_password" 
                                       required>
                                <small>Re-enter the password to confirm</small>
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label for="role">
                                    <i class="fas fa-user-tag"></i> Role *
                                </label>
                                <select id="role" name="role" required>
                                    <option value="">Select Role</option>
                                    <option value="Admin" <?php echo (isset($_POST['role']) && $_POST['role'] === 'Admin') ? 'selected' : ''; ?>>Admin</option>
                                    <option value="Manager" <?php echo (isset($_POST['role']) && $_POST['role'] === 'Manager') ? 'selected' : ''; ?>>Manager</option>
                                    <?php if ($current_admin['role'] === 'Super Admin'): ?>
                                        <option value="Super Admin" <?php echo (isset($_POST['role']) && $_POST['role'] === 'Super Admin') ? 'selected' : ''; ?>>Super Admin</option>
                                    <?php endif; ?>
                                </select>
                                <small>
                                    <strong>Admin:</strong> Full system access<br>
                                    <strong>Manager:</strong> Limited administrative access<br>
                                    <?php if ($current_admin['role'] === 'Super Admin'): ?>
                                        <strong>Super Admin:</strong> Complete system control
                                    <?php endif; ?>
                                </small>
                            </div>
                            
                            <div class="form-group">
                                <label for="status">
                                    <i class="fas fa-toggle-on"></i> Status *
                                </label>
                                <select id="status" name="status" required>
                                    <option value="">Select Status</option>
                                    <option value="Active" <?php echo (isset($_POST['status']) && $_POST['status'] === 'Active') ? 'selected' : ''; ?>>Active</option>
                                    <option value="Inactive" <?php echo (isset($_POST['status']) && $_POST['status'] === 'Inactive') ? 'selected' : ''; ?>>Inactive</option>
                                </select>
                                <small>Active administrators can log in and use the system</small>
                            </div>
                        </div>

                        <div class="btn-group">
                            <a href="admins.php" class="btn btn-secondary">
                                <i class="fas fa-arrow-left"></i> Back to Administrators
                            </a>
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-user-plus"></i> Create Administrator
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </main>
    </div>

    <script src="assets/js/admin.js"></script>
    <script>
        // Password confirmation validation
        document.getElementById('confirm_password').addEventListener('input', function() {
            const password = document.getElementById('password').value;
            const confirmPassword = this.value;
            
            if (password !== confirmPassword) {
                this.setCustomValidity('Passwords do not match');
            } else {
                this.setCustomValidity('');
            }
        });

        // Password strength indicator
        document.getElementById('password').addEventListener('input', function() {
            const password = this.value;
            const confirmPasswordField = document.getElementById('confirm_password');
            
            if (confirmPasswordField.value && password !== confirmPasswordField.value) {
                confirmPasswordField.setCustomValidity('Passwords do not match');
            } else {
                confirmPasswordField.setCustomValidity('');
            }
        });

        // Form validation
        document.querySelector('form').addEventListener('submit', function(e) {
            const password = document.getElementById('password').value;
            const confirmPassword = document.getElementById('confirm_password').value;
            
            if (password !== confirmPassword) {
                e.preventDefault();
                alert('Passwords do not match. Please check and try again.');
                return false;
            }
            
            if (password.length < 6) {
                e.preventDefault();
                alert('Password must be at least 6 characters long.');
                return false;
            }
        });
    </script>
</body>
</html>

