<?php
// register.php
declare(strict_types=1);
session_start();

require_once '../config/db_connect.php';

// Start output buffering
ob_start();

// Only admin can register new users
if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'admin') { 
    header('Location: login.php');
    exit; 
}

$message = '';
$message_type = '';

// Handle registration
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $fullname = trim($_POST['fullname']);
        $username = trim($_POST['username']);
        $password = $_POST['password'];
        $confirm_password = $_POST['confirm_password'];
        $role = $_POST['role'];
        $shop_id = (int)$_POST['shop_id'];
        
        // Validation
        if (empty($fullname) || empty($username) || empty($password)) {
            throw new Exception('All fields are required');
        }
        
        if ($password !== $confirm_password) {
            throw new Exception('Passwords do not match');
        }
        
        if (strlen($password) < 6) {
            throw new Exception('Password must be at least 6 characters');
        }
        
        // Check if username exists
        $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
        $stmt->execute([$username]);
        if ($stmt->fetch()) {
            throw new Exception('Username already exists');
        }
        
        // Hash password
        $password_hash = password_hash($password, PASSWORD_DEFAULT);
        
        // Insert user
        $stmt = $pdo->prepare("INSERT INTO users (username, password_hash, fullname, role, shop_id) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$username, $password_hash, $fullname, $role, $shop_id]);
        
        $message = 'User registered successfully!';
        $message_type = 'success';
        
        // Clear form
        $_POST = [];
        
    } catch (Exception $e) {
        $message = 'Error: ' . $e->getMessage();
        $message_type = 'danger';
    }
}

// Get active shops
$shops = $pdo->query("SELECT id, name FROM shops WHERE is_active = 1 ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register User - Pharmacy System</title>
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --primary-color: #667eea;
            --secondary-color: #764ba2;
            --success-color: #28a745;
            --light-bg: #f8f9fa;
        }
        
        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            padding: 20px;
        }
        
        .register-container {
            max-width: 500px;
            width: 100%;
            margin: 0 auto;
        }
        
        .register-card {
            border: none;
            border-radius: 20px;
            box-shadow: 0 15px 35px rgba(50, 50, 93, 0.1), 0 5px 15px rgba(0, 0, 0, 0.07);
            overflow: hidden;
            animation: fadeIn 0.6s ease;
        }
        
        .card-header {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
            color: white;
            padding: 30px;
            text-align: center;
            border-bottom: none;
        }
        
        .card-header h3 {
            margin: 0;
            font-weight: 600;
        }
        
        .card-body {
            padding: 40px;
            background: white;
        }
        
        .form-label {
            font-weight: 500;
            color: #495057;
            margin-bottom: 8px;
        }
        
        .form-control {
            border: 2px solid #e9ecef;
            border-radius: 10px;
            padding: 12px 15px;
            font-size: 14px;
            transition: all 0.3s ease;
        }
        
        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .btn-register {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
            border: none;
            border-radius: 10px;
            padding: 12px;
            font-weight: 500;
            font-size: 16px;
            letter-spacing: 0.5px;
            transition: all 0.3s ease;
        }
        
        .btn-register:hover {
            transform: translateY(-2px);
            box-shadow: 0 7px 14px rgba(50, 50, 93, 0.1), 0 3px 6px rgba(0, 0, 0, 0.08);
        }
        
        .role-badge {
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
            display: inline-block;
        }
        
        .badge-admin { background: #dc3545; color: white; }
        .badge-pharmacist { background: #17a2b8; color: white; }
        .badge-cashier { background: #6c757d; color: white; }
        
        .back-link {
            color: var(--primary-color);
            text-decoration: none;
            font-weight: 500;
            transition: color 0.3s ease;
        }
        
        .back-link:hover {
            color: var(--secondary-color);
        }
        
        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .password-strength {
            height: 5px;
            border-radius: 3px;
            margin-top: 5px;
            transition: all 0.3s ease;
        }
        
        .strength-0 { width: 0%; background: #dc3545; }
        .strength-1 { width: 25%; background: #dc3545; }
        .strength-2 { width: 50%; background: #ffc107; }
        .strength-3 { width: 75%; background: #17a2b8; }
        .strength-4 { width: 100%; background: #28a745; }
    </style>
</head>
<body>
    <div class="register-container">
        <div class="register-card">
            <div class="card-header">
                <h3><i class="fas fa-user-plus mr-2"></i> Register New User</h3>
                <p class="mb-0 mt-2 opacity-75">Add new staff members to the pharmacy system</p>
            </div>
            
            <div class="card-body">
                <?php if ($message): ?>
                <div class="alert alert-<?= $message_type ?> alert-dismissible fade show" role="alert">
                    <?= htmlspecialchars($message) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>
                
                <form method="POST" action="">
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <label class="form-label">Full Name *</label>
                            <input type="text" name="fullname" class="form-control" 
                                   value="<?= htmlspecialchars($_POST['fullname'] ?? '') ?>" 
                                   placeholder="John Doe" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Username *</label>
                            <input type="text" name="username" class="form-control" 
                                   value="<?= htmlspecialchars($_POST['username'] ?? '') ?>" 
                                   placeholder="johndoe" required>
                            <small class="text-muted">Used for login</small>
                        </div>
                    </div>
                    
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <label class="form-label">Password *</label>
                            <input type="password" name="password" id="password" class="form-control" 
                                   placeholder="••••••" required onkeyup="checkPasswordStrength()">
                            <div class="password-strength strength-0" id="passwordStrength"></div>
                            <small class="text-muted">Minimum 6 characters</small>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Confirm Password *</label>
                            <input type="password" name="confirm_password" class="form-control" 
                                   placeholder="••••••" required>
                        </div>
                    </div>
                    
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <label class="form-label">Role *</label>
                            <select name="role" class="form-control" required>
                                <option value="">Select Role</option>
                                <option value="cashier" <?= ($_POST['role'] ?? '') === 'cashier' ? 'selected' : '' ?>>Cashier</option>
                                <option value="pharmacist" <?= ($_POST['role'] ?? '') === 'pharmacist' ? 'selected' : '' ?>>Pharmacist</option>
                                <option value="admin" <?= ($_POST['role'] ?? '') === 'admin' ? 'selected' : '' ?>>Admin</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Assign to Shop *</label>
                            <select name="shop_id" class="form-control" required>
                                <option value="">Select Shop</option>
                                <?php foreach($shops as $shop): ?>
                                <option value="<?= $shop['id'] ?>" 
                                    <?= ($_POST['shop_id'] ?? '') == $shop['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($shop['name']) ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    
                    <div class="mb-4">
                        <h6 class="form-label">Role Permissions:</h6>
                        <div class="row">
                            <div class="col-md-4 text-center">
                                <span class="role-badge badge-admin">Admin</span>
                                <p class="small text-muted mb-0 mt-1">Full system access</p>
                            </div>
                            <div class="col-md-4 text-center">
                                <span class="role-badge badge-pharmacist">Pharmacist</span>
                                <p class="small text-muted mb-0 mt-1">Inventory & sales</p>
                            </div>
                            <div class="col-md-4 text-center">
                                <span class="role-badge badge-cashier">Cashier</span>
                                <p class="small text-muted mb-0 mt-1">Sales only</p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-register text-white">
                            <i class="fas fa-user-plus mr-2"></i> Register User
                        </button>
                        <a href="shops.php" class="btn btn-light">
                            <i class="fas fa-arrow-left mr-2"></i> Back to Shops
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Bootstrap 5 JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
    function checkPasswordStrength() {
        const password = document.getElementById('password').value;
        const strengthBar = document.getElementById('passwordStrength');
        
        let strength = 0;
        
        // Length check
        if (password.length >= 6) strength++;
        if (password.length >= 8) strength++;
        
        // Complexity checks
        if (/[A-Z]/.test(password)) strength++;
        if (/[0-9]/.test(password)) strength++;
        if (/[^A-Za-z0-9]/.test(password)) strength++;
        
        // Cap at 4
        strength = Math.min(strength, 4);
        
        // Update strength bar
        strengthBar.className = 'password-strength strength-' + strength;
    }
    
    // Initialize
    document.addEventListener('DOMContentLoaded', function() {
        checkPasswordStrength();
    });
    </script>
</body>
</html>

<?php ob_end_flush(); ?>