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

// Check if ID is provided
if (!isset($_GET['id'])) {
    header("Location: manage-team.php");
    exit();
}

$id = intval($_GET['id']);
$res = $conn->query("SELECT * FROM team_grovia WHERE id = $id");
$member = $res->fetch_assoc();

if (!$member) {
    die("Team member not found.");
}

// Fetch users for the linking dropdown
$users_res = $conn->query("SELECT id, name, email FROM users ORDER BY id ASC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit 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; }
        .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-update { background: var(--accent); color: #fff; border: none; padding: 15px; border-radius: 6px; cursor: pointer; font-weight: bold; width: 100%; font-size: 16px; }
        
        #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 'side-bar.php'; ?>
<?php include_once 'top-bar.php'; ?>

<div class="main-content">
    <div class="form-card">
        <h2 style="margin:0 0 25px 0;">Edit Team Member</h2>
        
        <form id="editTeamForm">
            <input type="hidden" name="id" value="<?php echo $member['id']; ?>">

            <div class="grid-2">
                <div>
                    <label>Employee ID</label>
                    <input type="text" value="<?php echo $member['emp_id']; ?>" readonly style="background:#f9f9f9; color:#7f8c8d;">
                </div>
                <div>
                    <label>Role</label>
                    <select name="role">
                        <?php 
                        $roles = ['Admin', 'Moderator', 'Support', 'Editor'];
                        foreach($roles as $r) {
                            $selected = ($member['role'] == $r) ? 'selected' : '';
                            echo "<option value='$r' $selected>$r</option>";
                        }
                        ?>
                    </select>
                </div>
            </div>

            <div class="grid-2">
                <div>
                    <label>User Name</label>
                    <input type="text" name="user_name" value="<?php echo htmlspecialchars($member['user_name']); ?>" required>
                </div>
                <div>
                    <label>New Password (Leave blank to keep current)</label>
                    <input type="password" name="password" placeholder="••••••••">
                </div>
            </div>

            <div class="grid-2">
                <div>
                    <label>Mobile Number</label>
                    <input type="text" name="mobile_number" value="<?php echo htmlspecialchars($member['mobile_number']); ?>">
                </div>
                <div>
                    <label>Linked User Account</label>
                    <select name="user_id">
                        <option value="">-- No User Linked --</option>
                        <?php while($u = $users_res->fetch_assoc()): ?>
                            <?php $selected = ($member['user_id'] == $u['id']) ? 'selected' : ''; ?>
                            <option value="<?php echo $u['id']; ?>" <?php echo $selected; ?>><?php echo $u['full_name']; ?></option>
                        <?php endwhile; ?>
                    </select>
                </div>
            </div>

            <button type="submit" class="btn-update" id="submitBtn">Update Member Details</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('editTeamForm').onsubmit = async (e) => {
    e.preventDefault();
    const btn = document.getElementById('submitBtn');
    const overlay = document.getElementById('responseOverlay');
    const timerSpan = document.getElementById('timer');
    
    btn.innerText = "Saving Changes...";
    btn.disabled = true;

    try {
        const res = await fetch('api/update-team-member.php', { 
            method: 'POST', 
            body: new FormData(e.target) 
        });
        const data = await res.json();

        overlay.style.display = "flex";
        if(data.success) {
            document.getElementById('statusIcon').innerHTML = "⚙️";
            document.getElementById('statusTitle').innerText = "Member Updated";
            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('statusDesc').innerText = data.message;
            setTimeout(() => { overlay.style.display = "none"; btn.disabled = false; }, 3000);
        }
    } catch (err) {
        alert("Update failed.");
        btn.disabled = false;
    }
};
</script>
</body>
</html>