<?php 
session_start();
require_once 'config/auth_check.php';
require_once 'config/db.php';

// Generate the next Employee ID (GVEMP0001)
$res = $conn->query("SELECT MAX(id) as last_id FROM team_grovia");
$row = $res->fetch_assoc();
$next_num = ($row['last_id'] ?? 0) + 1;
$emp_id = "GVEMP" . str_pad($next_num, 4, '0', STR_PAD_LEFT);

// Fetch existing users to link (optional)
$users_res = $conn->query("SELECT id, name, email FROM users ORDER BY name ASC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add Team Member | Grovia Admin</title>
    <style>
        :root { --sidebar-bg: #3b4368; --accent: #3498db; --bg: #f4f7f6; }
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background: var(--bg); display: flex; }
        .sidebar { width: 280px; background: var(--sidebar-bg); height: 100vh; position: fixed; color: #fff; }
        .main-content { margin-left: 280px; width: 100%; padding: 40px; }
        .form-card { background: #fff; padding: 35px; border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); max-width: 700px; margin: auto; }
        
        label { display: block; margin-bottom: 8px; font-weight: 600; color: #444; font-size: 11px; text-transform: uppercase; }
        input, select { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; margin-bottom: 20px; }
        
        .grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        .btn-save { background: #2ecc71; color: #fff; border: none; padding: 15px; border-radius: 6px; cursor: pointer; font-weight: bold; width: 100%; font-size: 16px; transition: 0.3s; }
        .btn-save:hover { background: #27ae60; }

        /* Response Overlay */
        #responseOverlay { display:none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 9999; align-items: center; justify-content: center; }
        .modal-content { background: white; padding: 40px; border-radius: 15px; text-align: center; max-width: 400px; width: 90%; }
    </style>
</head>
<body>

<?php include_once 'top-bar.php'; ?>
<?php include_once 'side-bar.php'; ?>
<div class="main-content">
    <div class="form-card">
        <h2 style="margin:0 0 25px 0;">Add New Team Member</h2>
        
        <form id="addTeamForm">
            <div class="grid-2">
                <div>
                    <label>Employee ID</label>
                    <input type="text" name="emp_id" value="<?php echo $emp_id; ?>" readonly style="background:#f9f9f9; color:var(--accent); font-weight:bold;">
                </div>
                <div>
                    <label>Role</label>
                    <select name="role">
                        <option value="Editor">Editor</option>
                        <option value="Support">Support</option>
                        <option value="Moderator">Moderator</option>
                        <option value="Admin">Admin</option>
                    </select>
                </div>
            </div>

            <div class="grid-2">
                <div>
                    <label>User Name (Login ID)</label>
                    <input type="text" name="user_name" placeholder="e.g. lovekesh_admin" required>
                </div>
                <div>
                    <label>Password</label>
                    <input type="password" name="password" placeholder="••••••••" required>
                </div>
            </div>

            <div class="grid-2">
                <div>
                    <label>Mobile Number</label>
                    <input type="text" name="mobile_number" placeholder="+91 00000 00000">
                </div>
                <div>
                    <label>Link to User Account (Optional)</label>
                    <select name="user_id">
                        <option value="">-- No User Linked --</option>
                        <?php while($u = $users_res->fetch_assoc()): ?>
                            <option value="<?php echo $u['id']; ?>"><?php echo $u['name']; ?> (<?php echo $u['email']; ?>)</option>
                        <?php endwhile; ?>
                    </select>
                </div>
            </div>

            <button type="submit" class="btn-save" id="submitBtn">Register Staff Member</button>
        </form>
    </div>
</div>

<div id="responseOverlay">
    <div class="modal-content">
        <div id="statusIcon" style="font-size: 50px; margin-bottom: 20px;"></div>
        <h3 id="statusTitle" style="margin:0; color:#333;"></h3>
        <p id="statusDesc" style="color:#666; margin: 10px 0 20px 0;"></p>
        <div style="font-size:12px; color:#aaa;">Redirecting in <span id="timer">3</span> seconds...</div>
    </div>
</div>

<script>
document.getElementById('addTeamForm').onsubmit = async (e) => {
    e.preventDefault();
    const btn = document.getElementById('submitBtn');
    const overlay = document.getElementById('responseOverlay');
    const timerSpan = document.getElementById('timer');
    
    btn.innerText = "Securing Credentials...";
    btn.disabled = true;

    const formData = new FormData(e.target);

    try {
        const res = await fetch('api/save-team-member.php', { method: 'POST', body: formData });
        const data = await res.json();

        overlay.style.display = "flex";
        if(data.success) {
            document.getElementById('statusIcon').innerHTML = "👤";
            document.getElementById('statusTitle').innerText = "Team Member Added";
            document.getElementById('statusDesc').innerText = data.message;
            let count = 3;
            const interval = setInterval(() => {
                count--; timerSpan.innerText = count;
                if(count === 0) { clearInterval(interval); window.location.href = 'manage-team.php'; }
            }, 1000);
        } else {
            document.getElementById('statusIcon').innerHTML = "❌";
            document.getElementById('statusTitle').innerText = "Registration Failed";
            document.getElementById('statusDesc').innerText = data.message;
            setTimeout(() => { overlay.style.display = "none"; btn.disabled = false; btn.innerText = "Register Staff Member"; }, 3000);
        }
    } catch (err) {
        alert("Network error.");
        btn.disabled = false;
    }
};
</script>
</body>
</html>