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

if (!isset($_GET['id'])) { 
    header("Location: manage-users.php"); 
    exit; 
}

$id = intval($_GET['id']);

// 1. Fetch User Data from the 'users' table
$user_res = $conn->query("SELECT * FROM users WHERE id = $id");
$user = $user_res->fetch_assoc();

if (!$user) { 
    die("User not found."); 
}

// 2. Fetch Companies for the dropdown
$companies = $conn->query("SELECT id, company_name FROM company ORDER BY company_name ASC");

// 3. Logic to check if existing rank is "Custom"
$is_custom = !in_array($user['rank'], ['Associate', 'Manager']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit User | 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 Styling */
        .sidebar { width: 280px; background: var(--sidebar-bg); height: 100vh; position: fixed; color: #fff; }
        .logo-area { padding: 30px; text-align: center; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .menu-link { display: block; padding: 18px 25px; color: #fff; text-decoration: none; border-bottom: 1px solid rgba(255,255,255,0.1); font-size: 16px; transition: 0.3s; }
        .menu-link:hover { background: #4a537d; }
        
        /* Form Content Area */
        .main-content { margin-left: 280px; width: 100%; padding: 40px; }
        .edit-card { background: #fff; padding: 40px; border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); max-width: 900px; margin: auto; }
        .form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        
        label { display: block; margin-bottom: 8px; font-weight: 600; color: #444; font-size: 13px; text-transform: uppercase; }
        input, select { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; }
        
        .btn-update { background: var(--accent); color: #fff; border: none; padding: 15px; border-radius: 6px; cursor: pointer; font-weight: bold; font-size: 16px; margin-top: 25px; width: 100%; }
        .alert { padding: 15px; border-radius: 6px; margin-bottom: 25px; display: none; }
        .alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
    </style>
</head>
<body>

<?php include 'top-bar.php'; ?>
<div class="sidebar">
    <div class="logo-area"><h2>GROVIA</h2></div>
    <a href="manage-users.php" class="menu-link">← Back to Users</a>
</div>

<div class="main-content">
    <div class="edit-card">
        <h2 style="margin-top:0;">Edit Profile: <?php echo htmlspecialchars($user['name']); ?></h2>
        <div id="responseMsg" class="alert alert-success"></div>

        <form id="editUserForm">
            <input type="hidden" name="id" value="<?php echo $user['id']; ?>">
            
            <div class="form-grid">
                <div>
                    <label>Full Name</label>
                    <input type="text" name="name" value="<?php echo htmlspecialchars($user['name']); ?>" required>
                </div>
                <div>
                    <label>Email Address</label>
                    <input type="email" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" required>
                </div>
                <div>
                    <label>Mobile Number</label>
                    <input type="text" name="mobile" value="<?php echo htmlspecialchars($user['mobile']); ?>" required>
                </div>
                <div>
                    <label>Gender</label>
                    <select name="gender">
                        <option value="Male" <?php if($user['gender'] == 'Male') echo 'selected'; ?>>Male</option>
                        <option value="Female" <?php if($user['gender'] == 'Female') echo 'selected'; ?>>Female</option>
                    </select>
                </div>
                <div>
                    <label>City</label>
                    <input type="text" name="city" value="<?php echo htmlspecialchars($user['city']); ?>">
                </div>
                <div>
                    <label>State</label>
                    <input type="text" name="state" value="<?php echo htmlspecialchars($user['state']); ?>">
                </div>
                <div>
                    <label>User Rank</label>
                    <select name="rank" id="rankSelect" onchange="toggleCustomRank()">
                        <option value="Associate" <?php if($user['rank'] == 'Associate') echo 'selected'; ?>>Associate</option>
                        <option value="Manager" <?php if($user['rank'] == 'Manager') echo 'selected'; ?>>Manager</option>
                        <option value="Custom" <?php if($is_custom) echo 'selected'; ?>>-- Custom Rank --</option>
                    </select>
                </div>
                
                <div id="customRankWrapper" style="display: <?php echo $is_custom ? 'block' : 'none'; ?>;">
                    <label>Enter Custom Rank</label>
                    <input type="text" name="custom_rank" id="customRankInput" 
                           value="<?php echo $is_custom ? htmlspecialchars($user['rank']) : ''; ?>"
                           placeholder="e.g. Supervisor">
                </div>

                <div style="grid-column: span 2;">
                    <label>Assigned Company</label>
                    <select name="company">
                        <option value="0">No Company Assigned</option>
                        <?php while($c = $companies->fetch_assoc()): ?>
                            <option value="<?php echo $c['id']; ?>" <?php if($user['company'] == $c['id']) echo 'selected'; ?>>
                                <?php echo htmlspecialchars($c['company_name']); ?>
                            </option>
                        <?php endwhile; ?>
                    </select>
                </div>
            </div>

            <button type="submit" class="btn-update">Update User Account</button>
        </form>
    </div>
</div>

<script>
function toggleCustomRank() {
    const select = document.getElementById('rankSelect');
    const wrapper = document.getElementById('customRankWrapper');
    const input = document.getElementById('customRankInput');

    if (select.value === 'Custom') {
        wrapper.style.display = 'block';
        input.setAttribute('required', 'required');
    } else {
        wrapper.style.display = 'none';
        input.removeAttribute('required');
    }
}

document.getElementById('editUserForm').onsubmit = async (e) => {
    e.preventDefault();
    const btn = e.target.querySelector('button');
    btn.innerText = 'Saving Changes...';
    btn.disabled = true;

    const res = await fetch('api/update-user.php', {
        method: 'POST',
        body: new FormData(e.target)
    });
    
    const data = await res.json();
    const msgDiv = document.getElementById('responseMsg');
    msgDiv.style.display = 'block';
    msgDiv.innerText = data.message;
    
    if(data.success) {
        window.scrollTo(0,0);
        setTimeout(() => { window.location.href = 'manage-users.php'; }, 1500);
    } else {
        btn.innerText = 'Update User Account';
        btn.disabled = false;
    }
};
</script>
</body>
</html>