<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/menu_config.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in and has Super Admin role
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Get user details and role verification
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if (!$user_details || $user_details['role_name'] !== 'Super Admin') {
    header('Location: dashboard.php');
    exit();
}

$full_name = $user_details['full_name'];
$role_name = $user_details['role_name'];

// Handle form submission
$message = '';
$message_type = '';
$form_data = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Collect form data
    $form_data = [
        'username' => trim($_POST['username']),
        'email' => trim($_POST['email']),
        'full_name' => trim($_POST['full_name']),
        'phone' => trim($_POST['phone']),
        'role_id' => (int)$_POST['role_id'],
        'password' => $_POST['password'],
        'confirm_password' => $_POST['confirm_password'],
        'status' => $_POST['status']
    ];
    
    $errors = [];
    
    // Validation
    if (empty($form_data['username'])) {
        $errors[] = "Username is required";
    } elseif (strlen($form_data['username']) < 3) {
        $errors[] = "Username must be at least 3 characters";
    }
    
    if (empty($form_data['email'])) {
        $errors[] = "Email is required";
    } elseif (!filter_var($form_data['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format";
    }
    
    if (empty($form_data['full_name'])) {
        $errors[] = "Full name is required";
    }
    
    if (empty($form_data['password'])) {
        $errors[] = "Password is required";
    } elseif (strlen($form_data['password']) < 6) {
        $errors[] = "Password must be at least 6 characters";
    }
    
    if ($form_data['password'] !== $form_data['confirm_password']) {
        $errors[] = "Passwords do not match";
    }
    
    if ($form_data['role_id'] <= 0) {
        $errors[] = "Please select a valid role";
    }
    
    // Check for existing username/email
    if (empty($errors)) {
        $sql_check = "SELECT user_id FROM users WHERE username = ? OR email = ?";
        $stmt_check = $conn->prepare($sql_check);
        $stmt_check->bind_param("ss", $form_data['username'], $form_data['email']);
        $stmt_check->execute();
        
        if ($stmt_check->get_result()->num_rows > 0) {
            $errors[] = "Username or email already exists";
        }
    }
    
    // Insert user if no errors
    if (empty($errors)) {
        $hashed_password = password_hash($form_data['password'], PASSWORD_DEFAULT);
        
        $sql_insert = "INSERT INTO users (username, email, full_name, phone, password, role_id, status) 
                       VALUES (?, ?, ?, ?, ?, ?, ?)";
        $stmt_insert = $conn->prepare($sql_insert);
        $stmt_insert->bind_param("sssssis", 
            $form_data['username'], 
            $form_data['email'], 
            $form_data['full_name'], 
            $form_data['phone'], 
            $hashed_password, 
            $form_data['role_id'], 
            $form_data['status']
        );
        
        if ($stmt_insert->execute()) {
            $new_user_id = $conn->insert_id;
            $message = "User created successfully! User ID: $new_user_id";
            $message_type = "success";
            $form_data = []; // Clear form on success
        } else {
            $message = "Error creating user: " . $conn->error;
            $message_type = "error";
        }
    } else {
        $message = implode('<br>', $errors);
        $message_type = "error";
    }
}

// Get user roles for dropdown
$sql_roles = "SELECT role_id, role_name, description FROM user_roles ORDER BY role_name";
$result_roles = $conn->query($sql_roles);

// Get recent users for reference
$sql_recent_users = "SELECT 
    u.user_id,
    u.username,
    u.full_name,
    u.email,
    u.status,
    ur.role_name,
    u.created_at
FROM users u
INNER JOIN user_roles ur ON u.role_id = ur.role_id
ORDER BY u.created_at DESC
LIMIT 5";
$result_recent = $conn->query($sql_recent_users);

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Add User - User Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        /* Header Section */
        .page-header {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }
        
        .header-title h1 {
            font-size: 1.875rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .header-subtitle {
            opacity: 0.9;
            font-size: 1rem;
        }
        
        .header-actions {
            display: flex;
            gap: 1rem;
        }
        
        .btn-secondary {
            background: rgba(255, 255, 255, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 600;
            transition: all 0.2s ease;
        }
        
        .btn-secondary:hover {
            background: rgba(255, 255, 255, 0.3);
            color: white;
            transform: translateY(-1px);
        }
        
        /* Alert Messages */
        .alert {
            padding: 1rem 1.5rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
            border: none;
            font-weight: 500;
        }
        
        .alert-success {
            background: #dcfce7;
            color: #166534;
            border-left: 4px solid #22c55e;
        }
        
        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }
        
        /* Main Content Layout */
        .content-grid {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 2rem;
        }
        
        /* Form Section */
        .form-card {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
        }
        
        .form-title {
            font-size: 1.25rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .form-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1.5rem;
            margin-bottom: 1.5rem;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-group.full-width {
            grid-column: 1 / -1;
        }
        
        .form-label {
            font-size: 0.875rem;
            font-weight: 600;
            color: #374151;
            margin-bottom: 0.5rem;
            display: block;
        }
        
        .form-label.required::after {
            content: ' *';
            color: #ef4444;
        }
        
        .form-control {
            width: 100%;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
            transition: border-color 0.2s ease;
        }
        
        .form-control:focus {
            border-color: #10b981;
            box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
            outline: none;
        }
        
        .form-help {
            font-size: 0.75rem;
            color: #64748b;
            margin-top: 0.25rem;
        }
        
        .password-requirements {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-top: 0.5rem;
        }
        
        .password-requirements h6 {
            font-size: 0.875rem;
            font-weight: 600;
            color: #374151;
            margin-bottom: 0.5rem;
        }
        
        .password-requirements ul {
            margin: 0;
            padding-left: 1.25rem;
            font-size: 0.75rem;
            color: #64748b;
        }
        
        /* Buttons */
        .form-actions {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;
            margin-top: 2rem;
            padding-top: 1.5rem;
            border-top: 1px solid #e2e8f0;
        }
        
        .btn-success {
            background: #10b981;
            border: 1px solid #10b981;
            color: white;
            padding: 0.75rem 2rem;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-success:hover {
            background: #059669;
            border-color: #059669;
            transform: translateY(-1px);
        }
        
        .btn-outline {
            background: transparent;
            border: 1px solid #d1d5db;
            color: #374151;
            padding: 0.75rem 2rem;
            border-radius: 8px;
            font-weight: 600;
            text-decoration: none;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-outline:hover {
            background: #f3f4f6;
            border-color: #9ca3af;
        }
        
        /* Recent Users Section */
        .recent-users-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
        }
        
        .card-title {
            font-size: 1.125rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .user-item {
            display: flex;
            align-items: center;
            gap: 1rem;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 0.75rem;
            transition: all 0.2s ease;
        }
        
        .user-item:hover {
            background: #f8fafc;
        }
        
        .user-item:last-child {
            margin-bottom: 0;
        }
        
        .user-avatar-sm {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            background: #6366f1;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.875rem;
            flex-shrink: 0;
        }
        
        .user-info-sm {
            flex: 1;
            min-width: 0;
        }
        
        .user-name-sm {
            font-weight: 600;
            color: #1e293b;
            font-size: 0.875rem;
            margin-bottom: 0.25rem;
        }
        
        .user-role-sm {
            font-size: 0.75rem;
            color: #64748b;
        }
        
        .status-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.7rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .status-active { background: #dcfce7; color: #166534; }
        .status-inactive { background: #f3f4f6; color: #374151; }
        .status-suspended { background: #fee2e2; color: #991b1b; }
        
        /* Role Selection Visual */
        .role-option {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 0.75rem;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .role-option:hover {
            border-color: #10b981;
            background: #f0fdf4;
        }
        
        .role-option.selected {
            border-color: #10b981;
            background: #dcfce7;
        }
        
        .role-option input[type="radio"] {
            margin-right: 0.75rem;
            transform: scale(1.2);
        }
        
        .role-name {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }
        
        .role-description {
            font-size: 0.875rem;
            color: #64748b;
            line-height: 1.4;
        }
        
        /* Responsive Design */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .content-grid {
                grid-template-columns: 1fr;
                gap: 1.5rem;
            }
            
            .form-grid {
                grid-template-columns: 1fr;
            }
            
            .header-content {
                flex-direction: column;
                text-align: center;
            }
            
            .form-actions {
                flex-direction: column;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="header-content">
                            <div class="header-title">
                                <h1>Add New User</h1>
                                <div class="header-subtitle">Create a new system user account</div>
                            </div>
                            <div class="header-actions">
                                <a href="list_users.php" class="btn-secondary">
                                    <i class="ph-arrow-left"></i> Back to Users
                                </a>
                                <a href="user_roles.php" class="btn-secondary">
                                    <i class="ph-users"></i> Manage Roles
                                </a>
                            </div>
                        </div>
                    </div>

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

                    <!-- Main Content -->
                    <div class="content-grid">
                        <!-- Add User Form -->
                        <div class="form-card">
                            <h2 class="form-title">User Information</h2>
                            
                            <form method="POST" id="addUserForm">
                                <div class="form-grid">
                                    <div class="form-group">
                                        <label class="form-label required">Full Name</label>
                                        <input type="text" name="full_name" class="form-control" 
                                               placeholder="Enter full name" 
                                               value="<?php echo htmlspecialchars($form_data['full_name'] ?? ''); ?>" required>
                                        <div class="form-help">Employee's complete name</div>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label class="form-label required">Username</label>
                                        <input type="text" name="username" class="form-control" 
                                               placeholder="Enter username" 
                                               value="<?php echo htmlspecialchars($form_data['username'] ?? ''); ?>" required>
                                        <div class="form-help">Must be unique, min 3 characters</div>
                                    </div>
                                </div>
                                
                                <div class="form-grid">
                                    <div class="form-group">
                                        <label class="form-label required">Email Address</label>
                                        <input type="email" name="email" class="form-control" 
                                               placeholder="user@quickwash.co.ke" 
                                               value="<?php echo htmlspecialchars($form_data['email'] ?? ''); ?>" required>
                                        <div class="form-help">Valid email address required</div>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label class="form-label">Phone Number</label>
                                        <input type="tel" name="phone" class="form-control" 
                                               placeholder="+254xxxxxxxxx" 
                                               value="<?php echo htmlspecialchars($form_data['phone'] ?? ''); ?>">
                                        <div class="form-help">Optional contact number</div>
                                    </div>
                                </div>
                                
                                <div class="form-group full-width">
                                    <label class="form-label required">User Role</label>
                                    <div class="role-selection">
                                        <?php while($role = $result_roles->fetch_assoc()): ?>
                                        <div class="role-option" onclick="selectRole(<?php echo $role['role_id']; ?>)">
                                            <input type="radio" name="role_id" value="<?php echo $role['role_id']; ?>" 
                                                   id="role_<?php echo $role['role_id']; ?>"
                                                   <?php echo (isset($form_data['role_id']) && $form_data['role_id'] == $role['role_id']) ? 'checked' : ''; ?> required>
                                            <div>
                                                <div class="role-name"><?php echo htmlspecialchars($role['role_name']); ?></div>
                                                <div class="role-description"><?php echo htmlspecialchars($role['description'] ?: 'No description available'); ?></div>
                                            </div>
                                        </div>
                                        <?php endwhile; ?>
                                    </div>
                                </div>
                                
                                <div class="form-grid">
                                    <div class="form-group">
                                        <label class="form-label required">Password</label>
                                        <input type="password" name="password" class="form-control" 
                                               placeholder="Enter password" required>
                                        <div class="password-requirements">
                                            <h6>Password Requirements:</h6>
                                            <ul>
                                                <li>Minimum 6 characters</li>
                                                <li>Recommended: Mix of letters and numbers</li>
                                                <li>User can change password after first login</li>
                                            </ul>
                                        </div>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label class="form-label required">Confirm Password</label>
                                        <input type="password" name="confirm_password" class="form-control" 
                                               placeholder="Confirm password" required>
                                        <div class="form-help">Must match the password above</div>
                                    </div>
                                </div>
                                
                                <div class="form-group">
                                    <label class="form-label required">Account Status</label>
                                    <select name="status" class="form-control" required>
                                        <option value="ACTIVE" <?php echo (isset($form_data['status']) && $form_data['status'] === 'ACTIVE') ? 'selected' : 'selected'; ?>>
                                            Active - User can login immediately
                                        </option>
                                        <option value="INACTIVE" <?php echo (isset($form_data['status']) && $form_data['status'] === 'INACTIVE') ? 'selected' : ''; ?>>
                                            Inactive - User cannot login
                                        </option>
                                    </select>
                                    <div class="form-help">Set initial account status</div>
                                </div>
                                
                                <div class="form-actions">
                                    <a href="list_users.php" class="btn-outline">Cancel</a>
                                    <button type="submit" class="btn-success">
                                        <i class="ph-plus"></i> Create User
                                    </button>
                                </div>
                            </form>
                        </div>
                        
                        <!-- Recent Users -->
                        <div class="recent-users-card">
                            <h3 class="card-title">Recently Added Users</h3>
                            
                            <?php if ($result_recent->num_rows > 0): ?>
                                <?php while($recent_user = $result_recent->fetch_assoc()): ?>
                                <div class="user-item">
                                    <div class="user-avatar-sm">
                                        <?php echo strtoupper(substr($recent_user['full_name'], 0, 2)); ?>
                                    </div>
                                    <div class="user-info-sm">
                                        <div class="user-name-sm"><?php echo htmlspecialchars($recent_user['full_name']); ?></div>
                                        <div class="user-role-sm">
                                            <?php echo htmlspecialchars($recent_user['role_name']); ?> • 
                                            @<?php echo htmlspecialchars($recent_user['username']); ?>
                                        </div>
                                    </div>
                                    <div>
                                        <span class="status-badge status-<?php echo strtolower($recent_user['status']); ?>">
                                            <?php echo $recent_user['status']; ?>
                                        </span>
                                        <div style="font-size: 0.7rem; color: #64748b; margin-top: 0.25rem;">
                                            <?php echo date('M j, Y', strtotime($recent_user['created_at'])); ?>
                                        </div>
                                    </div>
                                </div>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <div style="text-align: center; padding: 2rem; color: #64748b;">
                                    <div style="font-size: 2rem; margin-bottom: 1rem;">👥</div>
                                    <div>No recent users found</div>
                                </div>
                            <?php endif; ?>
                            
                            <div style="margin-top: 1.5rem; padding-top: 1rem; border-top: 1px solid #e2e8f0;">
                                <a href="list_users.php" style="color: #6366f1; text-decoration: none; font-weight: 600; font-size: 0.875rem;">
                                    View All Users →
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Quick Access Links -->
                    <div style="background: white; border-radius: 12px; padding: 1.5rem; box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1); border: 1px solid #e2e8f0;">
                        <h3 style="font-size: 1.125rem; font-weight: 700; color: #1e293b; margin-bottom: 1rem;">
                            Quick Actions
                        </h3>
                        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem;">
                            <a href="list_users.php" style="display: flex; align-items: center; gap: 0.75rem; padding: 1rem; border: 1px solid #e2e8f0; border-radius: 8px; text-decoration: none; color: #374151; transition: all 0.2s ease;">
                                <div style="width: 40px; height: 40px; background: #e0e7ff; color: #4f46e5; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 1.25rem;">
                                    👥
                                </div>
                                <div>
                                    <div style="font-weight: 600;">View All Users</div>
                                    <div style="font-size: 0.75rem; color: #64748b;">Manage existing users</div>
                                </div>
                            </a>
                            
                            <a href="user_roles.php" style="display: flex; align-items: center; gap: 0.75rem; padding: 1rem; border: 1px solid #e2e8f0; border-radius: 8px; text-decoration: none; color: #374151; transition: all 0.2s ease;">
                                <div style="width: 40px; height: 40px; background: #fef3c7; color: #d97706; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 1.25rem;">
                                    🛡️
                                </div>
                                <div>
                                    <div style="font-weight: 600;">User Roles</div>
                                    <div style="font-size: 0.75rem; color: #64748b;">Manage user roles</div>
                                </div>
                            </a>
                            
                            <a href="activity_logs.php" style="display: flex; align-items: center; gap: 0.75rem; padding: 1rem; border: 1px solid #e2e8f0; border-radius: 8px; text-decoration: none; color: #374151; transition: all 0.2s ease;">
                                <div style="width: 40px; height: 40px; background: #dcfce7; color: #059669; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 1.25rem;">
                                    📋
                                </div>
                                <div>
                                    <div style="font-weight: 600;">Activity Logs</div>
                                    <div style="font-size: 0.75rem; color: #64748b;">View user activity</div>
                                </div>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <script>
        function selectRole(roleId) {
            // Remove selected class from all role options
            document.querySelectorAll('.role-option').forEach(option => {
                option.classList.remove('selected');
            });
            
            // Add selected class to clicked option
            document.querySelector(`#role_${roleId}`).closest('.role-option').classList.add('selected');
            
            // Check the radio button
            document.querySelector(`#role_${roleId}`).checked = true;
        }
        
        // Initialize role selection on page load
        document.addEventListener('DOMContentLoaded', function() {
            const checkedRole = document.querySelector('input[name="role_id"]:checked');
            if (checkedRole) {
                checkedRole.closest('.role-option').classList.add('selected');
            }
            
            // Add click handlers to role options
            document.querySelectorAll('.role-option').forEach(option => {
                option.addEventListener('click', function() {
                    const radio = this.querySelector('input[type="radio"]');
                    if (radio) {
                        selectRole(radio.value);
                    }
                });
            });
            
            // Password confirmation validation
            const password = document.querySelector('input[name="password"]');
            const confirmPassword = document.querySelector('input[name="confirm_password"]');
            
            function validatePasswords() {
                if (password.value && confirmPassword.value) {
                    if (password.value !== confirmPassword.value) {
                        confirmPassword.setCustomValidity('Passwords do not match');
                    } else {
                        confirmPassword.setCustomValidity('');
                    }
                }
            }
            
            password.addEventListener('input', validatePasswords);
            confirmPassword.addEventListener('input', validatePasswords);
        });
    </script>
    
    <script src="assets/js/app.js"></script>
</body>
</html>