<?php
/**
 * Enterprise HRM ERP System - Create Admin User
 * Run this script once to create the initial admin user
 * DELETE THIS FILE AFTER USE FOR SECURITY
 */

require_once __DIR__ . '/../includes/init.php';

// Only allow this script to run if no admin users exist
try {
    $db = getDB();
    $stmt = $db->prepare("SELECT COUNT(*) FROM users WHERE role_id = 1");
    $stmt->execute();
    $adminCount = $stmt->fetchColumn();
    
    if ($adminCount > 0) {
        die("Admin user already exists. This script can only be run once. Please delete this file for security.");
    }
} catch (Exception $e) {
    die("Error checking for existing admin: " . $e->getMessage());
}

$error = null;
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = sanitize($_POST['username'] ?? '');
    $email = sanitize($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';
    $fullName = sanitize($_POST['full_name'] ?? '');
    
    // Validation
    if (empty($username) || empty($email) || empty($password) || empty($fullName)) {
        $error = 'All fields are required.';
    } elseif ($password !== $confirmPassword) {
        $error = 'Passwords do not match.';
    } else {
        $passwordErrors = validatePassword($password);
        if (!empty($passwordErrors)) {
            $error = implode(' ', $passwordErrors);
        } else {
            try {
                $db = getDB();
                $passwordHash = hashPassword($password);
                $siteId = 1; // Default site
                $roleId = 1; // Super Admin
                
                $stmt = $db->prepare("
                    INSERT INTO users (site_id, username, email, password_hash, full_name, role_id, user_status)
                    VALUES (?, ?, ?, ?, ?, ?, 'active')
                ");
                $stmt->execute([$siteId, $username, $email, $passwordHash, $fullName, $roleId]);
                
                $success = true;
                logAudit('CREATE', 'users', $db->lastInsertId(), null, ['username' => $username, 'email' => $email]);
            } catch (Exception $e) {
                error_log("Error creating admin: " . $e->getMessage());
                $error = 'An error occurred while creating the admin user.';
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Admin User - <?php echo getSetting('SYSTEM_NAME', APP_NAME); ?></title>
    <link rel="stylesheet" href="<?php echo BASE_URL; ?>/assets/css/style.css">
    <style>
        .setup-container {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .setup-box {
            background: white;
            padding: 40px;
            border-radius: 12px;
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
            width: 100%;
            max-width: 500px;
        }
        .setup-header {
            text-align: center;
            margin-bottom: 30px;
        }
        .setup-header h1 {
            font-size: 28px;
            color: var(--text-primary);
            margin-bottom: 10px;
        }
        .setup-header p {
            color: var(--text-secondary);
            font-size: 14px;
        }
        .alert-warning {
            background-color: #fef3c7;
            color: #92400e;
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 20px;
            border-left: 4px solid var(--warning-color);
        }
        .alert-success {
            background-color: #d1fae5;
            color: #065f46;
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 20px;
            border-left: 4px solid var(--success-color);
        }
    </style>
</head>
<body>
    <div class="setup-container">
        <div class="setup-box">
            <div class="setup-header">
                <h1>Create Admin User</h1>
                <p>Enterprise HRM ERP System - Initial Setup</p>
            </div>
            
            <?php if ($success): ?>
            <div class="alert-success">
                <strong>Success!</strong> Admin user created successfully. You can now login with your credentials.
                <br><br>
                <strong>IMPORTANT:</strong> Please delete this file (setup/create_admin.php) for security purposes.
                <br><br>
                <a href="<?php echo BASE_URL; ?>/login.php" class="btn btn-primary" style="display: inline-block; margin-top: 10px;">Go to Login</a>
            </div>
            <?php else: ?>
            <div class="alert-warning">
                <strong>Security Notice:</strong> This script will be disabled after creating the admin user. Please delete this file after use.
            </div>
            
            <?php if ($error): ?>
            <div class="alert alert-error">
                <?php echo htmlspecialchars($error); ?>
            </div>
            <?php endif; ?>
            
            <form method="POST" action="">
                <div class="form-group">
                    <label class="form-label" for="username">Username *</label>
                    <input type="text" id="username" name="username" class="form-control" required autofocus
                           value="<?php echo htmlspecialchars($username ?? ''); ?>">
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="email">Email *</label>
                    <input type="email" id="email" name="email" class="form-control" required
                           value="<?php echo htmlspecialchars($email ?? ''); ?>">
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="full_name">Full Name *</label>
                    <input type="text" id="full_name" name="full_name" class="form-control" required
                           value="<?php echo htmlspecialchars($fullName ?? ''); ?>">
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="password">Password *</label>
                    <input type="password" id="password" name="password" class="form-control" required>
                    <small style="color: var(--text-secondary); font-size: 12px;">
                        Minimum 8 characters, must include uppercase, lowercase, number, and special character.
                    </small>
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="confirm_password">Confirm Password *</label>
                    <input type="password" id="confirm_password" name="confirm_password" class="form-control" required>
                </div>
                
                <button type="submit" class="btn btn-primary" style="width: 100%;">Create Admin User</button>
            </form>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>

