<?php
require_once('../includes/functions.php');

if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') {
    header("Location: ../login.php");
    exit();
}

$message = '';
$error = '';
$aircraftTypes = getAircraftTypes();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $users = readJson('users');
    $newId = getNextId('users');
    
    $username = $_POST['username'];
    $password = $_POST['password'];
    
    if ($username !== strtolower($username)) {
        $error = "❌ Username must be in lowercase only! No uppercase letters allowed.";
    } elseif ($password !== strtolower($password)) {
        $error = "❌ Password must be in lowercase only! No uppercase letters allowed.";
    } else {
        $usernameExists = false;
        foreach ($users as $user) {
            if ($user['username'] === $username) {
                $usernameExists = true;
                break;
            }
        }
        
        if ($usernameExists) {
            $error = "❌ Username already exists! Please choose a different username.";
        } else {
            $endorsements = isset($_POST['endorsements']) ? $_POST['endorsements'] : [];
            
            $users[] = [
                'id' => $newId,
                'username' => $username,
                'password' => $password,
                'email' => $_POST['email'],
                'phone' => $_POST['phone'],
                'full_name' => $_POST['full_name'],
                'cycle' => $_POST['cycle'],
                'ame_license' => $_POST['ame_license'],
                'ame_expiry' => $_POST['ame_expiry'],
                'raic_number' => $_POST['raic_number'],
                'raic_expiry' => $_POST['raic_expiry'],
                'da_number' => $_POST['da_number'],
                'da_expiry' => $_POST['da_expiry'],
                'amo_stamp_number' => $_POST['amo_stamp_number'],
                'amo_stamp_expiry' => $_POST['amo_stamp_expiry'],
                'endorsements' => $endorsements,
                'is_active' => true,
                'role' => 'employee',
                'created_at' => date('Y-m-d H:i:s')
            ];
            
            writeJson('users', $users);
            $message = "✅ Employee added successfully! Username: $username, Password: $password";
        }
    }
}
?>
<?php include('../includes/header.php'); ?>
<style>
    .form-section {
        background: #fefcf8;
        border-radius: 20px;
        padding: 20px;
        margin-bottom: 24px;
        border: 1px solid #e2cfb3;
    }
    .form-section h3 {
        color: #6b1d2f;
        border-left: 4px solid #c9a87c;
        padding-left: 12px;
        margin-bottom: 20px;
        font-family: 'Georgia', serif;
    }
    .form-grid {
        display: grid;
        grid-template-columns: 1fr;
        gap: 16px;
    }
    @media (min-width: 768px) {
        .form-grid {
            grid-template-columns: 1fr 1fr;
        }
    }
    .checkbox-group {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
        gap: 12px;
        margin: 15px 0;
        padding: 15px;
        background: #faf3e8;
        border-radius: 16px;
        border: 1px solid #e2cfb3;
    }
    .checkbox-label {
        display: flex;
        align-items: center;
        gap: 8px;
        cursor: pointer;
        font-size: 0.9rem;
        color: #2c1e12;
    }
    .checkbox-label input[type="checkbox"] {
        width: 18px;
        height: 18px;
        margin: 0;
        accent-color: #6b1d2f;
    }
    .btn-sm {
        padding: 6px 12px;
        font-size: 0.8rem;
    }
    .error-box {
        background: #f2dbdb;
        border-left: 4px solid #a03e4b;
        padding: 15px;
        margin-bottom: 20px;
        border-radius: 12px;
        color: #6b1d2f;
    }
    .warning-note {
        background: #fae9d6;
        border-left: 4px solid #c9a87c;
        padding: 12px 15px;
        margin-bottom: 20px;
        border-radius: 12px;
        font-size: 0.85rem;
    }
</style>
<div class="sidebar">
    <h3>📋 Admin Console</h3>
    <a href="dashboard.php" class="btn">📊 Dashboard</a>
    <a href="add_user.php" class="btn active">👤 Add Crew</a>
    <a href="manage_users.php" class="btn">📋 Crew List</a>
    <a href="employee_list.php" class="btn">📋 Full Employee Data</a>
    <a href="employee_chart.php" class="btn">📊 Employee Chart</a>
    <a href="edit_user.php" class="btn">✏️ Edit Crew</a>
    <a href="manage_endorsements.php" class="btn">✈️ Endorsements</a>
    <a href="add_memo.php" class="btn">📝 New Memo</a>
    <a href="add_quiz.php" class="btn">📚 New Quiz</a>
    <a href="inbox.php" class="btn">📥 Safety Reports</a>
    <a href="chat.php" class="btn">💬 Group Chat</a>
    <a href="tools.php" class="btn">🔧 Tools Management</a>
    <a href="upload_manual.php" class="btn">📘 Upload Manual</a>
</div>
<div class="content">
    <h2>👤 Add New Crew Member</h2>
    
    <div class="warning-note">
        <strong>⚠️ Note:</strong> Username and password must be in <strong>lowercase only</strong> (a-z, 0-9, _).<br>
        📱 Credentials will be sent via SMS to the provided phone number.
    </div>
    
    <?php if($message): ?>
        <div class="alert alert-success"><?php echo $message; ?></div>
    <?php endif; ?>
    
    <?php if($error): ?>
        <div class="error-box"><?php echo $error; ?></div>
    <?php endif; ?>
    
    <form method="POST">
        <!-- Personal Information -->
        <div class="form-section">
            <h3>👤 Personal Information</h3>
            <div class="form-grid">
                <div>
                    <label>Full Name *</label>
                    <input type="text" name="full_name" required>
                </div>
                <div>
                    <label>Username * (lowercase only)</label>
                    <input type="text" name="username" id="username" required pattern="[a-z0-9_]+" placeholder="e.g., john_doe">
                    <small style="color:#8b7355;">Only a-z, 0-9, _ (no spaces)</small>
                </div>
                <div>
                    <label>Password * (lowercase only)</label>
                    <input type="text" name="password" id="password" value="password123" required pattern="[a-z0-9_]+">
                </div>
                <div>
                    <label>Email *</label>
                    <input type="email" name="email" required>
                </div>
                <div>
                    <label>Phone Number *</label>
                    <input type="tel" name="phone" required placeholder="+1 555 555 5555">
                    <small style="color:#8b7355;">Include country code (e.g., +1 for US/Canada)</small>
                </div>
                <div>
                    <label>Work Cycle *</label>
                    <select name="cycle" required>
                        <option value="Even">Even Cycle</option>
                        <option value="Odd">Odd Cycle</option>
                    </select>
                </div>
            </div>
        </div>
        
        <!-- Aviation Credentials -->
        <div class="form-section">
            <h3>✈️ Aviation Credentials</h3>
            <div class="form-grid">
                <div>
                    <label>AME License Number</label>
                    <input type="text" name="ame_license">
                    <label>AME Expiry Date</label>
                    <input type="date" name="ame_expiry">
                </div>
                <div>
                    <label>RAIC Number</label>
                    <input type="text" name="raic_number">
                    <label>RAIC Expiry Date</label>
                    <input type="date" name="raic_expiry">
                </div>
                <div>
                    <label>DA Number</label>
                    <input type="text" name="da_number">
                    <label>DA Expiry Date</label>
                    <input type="date" name="da_expiry">
                </div>
                <div>
                    <label>✈️ AMO Stamp Number</label>
                    <input type="text" name="amo_stamp_number" placeholder="e.g., AMO-2024-001">
                    <label>📅 AMO Stamp Expiry Date</label>
                    <input type="date" name="amo_stamp_expiry">
                </div>
            </div>
        </div>
        
        <!-- Aircraft Endorsements -->
        <div class="form-section">
            <h3>✈️ Aircraft Endorsements</h3>
            <div class="checkbox-group">
                <?php foreach($aircraftTypes as $name => $code): ?>
                    <label class="checkbox-label">
                        <input type="checkbox" name="endorsements[]" value="<?php echo $code; ?>">
                        <span><strong><?php echo $code; ?></strong> <small style="color:#8b7355;">(<?php echo $name; ?>)</small></span>
                    </label>
                <?php endforeach; ?>
            </div>
            <div style="margin-top: 12px;">
                <button type="button" class="btn btn-sm" onclick="selectAll()" style="background:#c9a87c; color:#2c1e12;">Select All</button>
                <button type="button" class="btn btn-sm" onclick="selectNone()" style="background:#e2cfb3; color:#2c1e12;">Select None</button>
            </div>
        </div>
        
        <button type="submit" class="btn btn-primary" style="background: #6b1d2f; color: #f9e4c2; width: 100%; padding: 14px; margin-top: 10px;">✈️ Add Crew Member</button>
    </form>
</div>

<script>
    function selectAll() {
        document.querySelectorAll('input[name="endorsements[]"]').forEach(cb => cb.checked = true);
    }
    function selectNone() {
        document.querySelectorAll('input[name="endorsements[]"]').forEach(cb => cb.checked = false);
    }
    
    const usernameField = document.getElementById('username');
    if (usernameField) {
        usernameField.addEventListener('input', function() {
            this.value = this.value.toLowerCase().replace(/[^a-z0-9_]/g, '');
        });
    }
    const passwordField = document.getElementById('password');
    if (passwordField) {
        passwordField.addEventListener('input', function() {
            this.value = this.value.toLowerCase().replace(/[^a-z0-9_]/g, '');
        });
    }
</script>

<div class="clearfix"></div>
<?php include('../includes/footer.php'); ?>