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

// Fetch Companies for the dropdown so you can assign a user to a company immediately
$companies = $conn->query("SELECT id, company_name FROM company ORDER BY company_name ASC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add New User | Grovia Admin</title>
    <style>
        :root { 
            --sidebar-bg: #3b4368; 
            --accent: #2ecc71; /* Green for "Add" actions */
            --bg: #f4f7f6; 
        }
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background: var(--bg); display: flex; }
        
        /* Sidebar Styles */
        .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); }
        
        /* Layout and Form */
        .main-content { margin-left: 280px; width: 100%; padding: 40px; }
        .form-card { background: #fff; padding: 30px; 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-submit { background: var(--accent); color: #fff; border: none; padding: 15px; border-radius: 6px; cursor: pointer; font-weight: bold; font-size: 16px; margin-top: 20px; width: 100%; transition: 0.3s; }
        .btn-submit:hover { background: #27ae60; }
        
        .alert { padding: 15px; border-radius: 6px; margin-bottom: 20px; display: none; }
        .alert-error { background: #f8d7da; color: #721c24; }
        .alert-success { background: #d4edda; color: #155724; }
    </style>
</head>
<body>

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

<div class="main-content">
    <div class="form-card">
        <h2 style="margin-top:0;">Register New User</h2>
        <div id="responseMsg" class="alert"></div>

        <form id="addUserForm">
            <div class="form-grid">
                <div>
                    <label>Full Name</label>
                    <input type="text" name="name" placeholder="Enter full name" required>
                </div>
                <div>
                    <label>Email Address</label>
                    <input type="email" name="email" placeholder="email@example.com" required>
                </div>
                <div>
                    <label>Mobile Number</label>
                    <input type="text" maxlength="10" name="mobile" placeholder="98XXXXXXXX" required>
                </div>
                <div>
                    <label>Login Pin (Password)</label>
                    <input type="password" name="pin" placeholder="Create a secure pin" required>
                </div>
                <div>
                    <label>Gender</label>
                    <select name="gender">
                        <option value="Male">Male</option>
                        <option value="Female">Female</option>
                    </select>
                </div>
                    <div>
                          <label>User Rank</label>
                          <select name="rank" id="rankSelect" onchange="toggleCustomRank()">
                              <option value="Associate">Associate</option>
                              <option value="Manager">Manager</option>
                              <option value="Custom">-- Set Custom Rank --</option>
                          </select>
                      </div>

                      <div id="customRankWrapper" style="display: none;">
                          <label>Enter Custom Rank</label>
                          <input type="text" name="custom_rank" id="customRankInput" placeholder="e.g. Bronze, Silver, Elite, Diamond, etc.">
                      </div>
                <div>
                    <label>City</label>
                    <input type="text" name="city" placeholder="City Name">
                </div>
                <div>
                    <label>State</label>
                    <input type="text" name="state" placeholder="State Name">
                </div>
                <div style="grid-column: span 2;">
                    <label>Assign to Company</label>
                    <select name="company" required>
                        <option value="">-- Select Company --</option>
                        <?php while($c = $companies->fetch_assoc()): ?>
                            <option value="<?php echo $c['id']; ?>"><?php echo htmlspecialchars($c['company_name']); ?></option>
                        <?php endwhile; ?>
                    </select>
                </div>
            </div>

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

<script>
// custom rank

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');
        input.focus();
    } else {
        wrapper.style.display = 'none';
        input.removeAttribute('required');
        input.value = ''; // Clear if they switch back
    }
}


document.getElementById('addUserForm').onsubmit = async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    
    const res = await fetch('api/save-user.php', {
        method: 'POST',
        body: formData
    });
    
    const data = await res.json();
    const msgDiv = document.getElementById('responseMsg');
    msgDiv.style.display = 'block';
    msgDiv.innerText = data.message;
    msgDiv.className = 'alert ' + (data.success ? 'alert-success' : 'alert-error');
    
    if(data.success) {
        e.target.reset();
        setTimeout(() => { window.location.href = 'manage-users.php'; }, 1500);
    }
};
</script>
</body>
</html>