<?php
session_start();
require_once 'config/database.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';
require_once 'includes/translation.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') {
    redirect('login.php');
}

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

$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $password = $_POST['password'];
    $full_name = trim($_POST['full_name']);
    $role = $_POST['role'];
    
    if (empty($username) || empty($email) || empty($password) || empty($full_name)) {
        $error = __('all_fields_required');
    } else {
        try {
            // Check if username or email already exists
            $stmt = $conn->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
            $stmt->execute([$username, $email]);
            
            if ($stmt->fetch()) {
                $error = __('username_or_email_exists');
            } else {
                // Insert new user
                $stmt = $conn->prepare("
                    INSERT INTO users (username, email, password, full_name, role) 
                    VALUES (?, ?, ?, ?, ?)
                ");
                $stmt->execute([$username, $email, $password, $full_name, $role]);
                
                logActivity($conn, $_SESSION['user_id'], __('add_new_user_activity'), 'users', $conn->lastInsertId());
                $message = __('user_added_successfully');
                
                // Clear form
                $_POST = [];
            }
        } catch (PDOException $e) {
            $error = __('error_adding_user') . ': ' . $e->getMessage();
        }
    }
}

// Set page title
$page_title = __('add_new_user') . ' - ' . __('system_name');

// Include header
include 'includes/header.php';
?>


    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h3 mb-0"><?php echo __('add_new_user'); ?></h1>
        <a href="settings.php" class="btn btn-secondary">
            <i class="fas fa-arrow-right"></i> <?php echo __('back_to_settings'); ?>
        </a>
    </div>

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

    <?php if ($error): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-triangle me-2"></i>
            <?php echo $error; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <div class="row">
        <!-- Form -->
        <div class="col-md-8">
            <div class="card shadow">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary"><?php echo __('user_information'); ?></h6>
                </div>
                <div class="card-body">
                    <form method="POST" class="needs-validation" novalidate>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="username" class="form-label"><?php echo __('username'); ?> *</label>
                                <input type="text" class="form-control" id="username" name="username" 
                                       placeholder="<?php echo __('enter_username'); ?>" value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>" required>
                                <div class="invalid-feedback">
                                    <?php echo __('please_enter_username'); ?>
                                </div>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label for="email" class="form-label"><?php echo __('email'); ?> *</label>
                                <input type="email" class="form-control" id="email" name="email" 
                                       placeholder="user@example.com" value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>" required>
                                <div class="invalid-feedback">
                                    <?php echo __('please_enter_valid_email'); ?>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="full_name" class="form-label"><?php echo __('full_name'); ?> *</label>
                                <input type="text" class="form-control" id="full_name" name="full_name" 
                                       placeholder="<?php echo __('enter_full_name'); ?>" value="<?php echo htmlspecialchars($_POST['full_name'] ?? ''); ?>" required>
                                <div class="invalid-feedback">
                                    <?php echo __('please_enter_full_name'); ?>
                                </div>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label for="role" class="form-label"><?php echo __('role'); ?> *</label>
                                <select class="form-select" id="role" name="role" required>
                                    <option value=""><?php echo __('select_role'); ?></option>
                                    <option value="admin" <?php echo ($_POST['role'] ?? '') == 'admin' ? 'selected' : ''; ?>><?php echo __('system_admin'); ?></option>
                                    <option value="pharmacist" <?php echo ($_POST['role'] ?? '') == 'pharmacist' ? 'selected' : ''; ?>><?php echo __('pharmacist'); ?></option>
                                    <option value="user" <?php echo ($_POST['role'] ?? '') == 'user' ? 'selected' : ''; ?>><?php echo __('regular_user'); ?></option>
                                </select>
                                <div class="invalid-feedback">
                                    <?php echo __('please_select_role'); ?>
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="password" class="form-label"><?php echo __('password'); ?> *</label>
                            <input type="password" class="form-control" id="password" name="password" 
                                   placeholder="<?php echo __('enter_password'); ?>" required minlength="6">
                            <div class="invalid-feedback">
                                <?php echo __('please_enter_password'); ?>
                            </div>
                            <div class="form-text"><?php echo __('password_min_length'); ?></div>
                        </div>

                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> <?php echo __('add_user_button'); ?>
                            </button>
                            <a href="settings.php" class="btn btn-secondary">
                                <i class="fas fa-times"></i> <?php echo __('cancel'); ?>
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Instructions -->
        <div class="col-md-4">
            <div class="card shadow">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-info"><?php echo __('user_roles'); ?></h6>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <h6 class="text-primary"><?php echo __('system_admin'); ?></h6>
                        <p class="small text-muted"><?php echo __('admin_role_description'); ?></p>
                    </div>
                    
                    <div class="mb-3">
                        <h6 class="text-success"><?php echo __('pharmacist'); ?></h6>
                        <p class="small text-muted"><?php echo __('pharmacist_role_description'); ?></p>
                    </div>
                    
                    <div class="mb-3">
                        <h6 class="text-info"><?php echo __('regular_user'); ?></h6>
                        <p class="small text-muted"><?php echo __('user_role_description'); ?></p>
                    </div>
                    
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <strong><?php echo __('warning'); ?>:</strong> <?php echo __('role_selection_warning'); ?>
                    </div>
                </div>
            </div>

            <div class="card shadow mt-3">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-warning"><?php echo __('password_requirements'); ?></h6>
                </div>
                <div class="card-body">
                    <ul class="list-unstyled mb-0">
                        <li><i class="fas fa-check text-success me-2"></i><?php echo __('min_6_characters'); ?></li>
                        <li><i class="fas fa-info text-info me-2"></i><?php echo __('use_letters_numbers'); ?></li>
                        <li><i class="fas fa-shield-alt text-warning me-2"></i><?php echo __('avoid_simple_passwords'); ?></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Form validation
(function() {
    'use strict';
    window.addEventListener('load', function() {
        var forms = document.getElementsByClassName('needs-validation');
        var validation = Array.prototype.filter.call(forms, function(form) {
            form.addEventListener('submit', function(event) {
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        });
    }, false);
})();

// Username validation (no spaces, special characters)
document.getElementById('username').addEventListener('input', function() {
    const username = this.value;
    const isValid = /^[a-zA-Z0-9_]+$/.test(username);
    
    if (username && !isValid) {
        this.setCustomValidity('<?php echo __('username_alphanumeric_only'); ?>');
    } else {
        this.setCustomValidity('');
    }
});
</script>

<?php include 'includes/footer.php'; ?>
