<?php
declare(strict_types=1);

/* ================= AUTH ================= */
require_once __DIR__ . '/../security/auth_guard_web.php';
require_once __DIR__ . '/../partials/main.php';
require_once __DIR__ . '/../config/database.php';

$db = Database::getInstance();

/**
 * Fetch roles lower than current user's role
 */
$stmt = $db->prepare("
    SELECT id, name
    FROM roles
    WHERE level < (
        SELECT r.level
        FROM employees e
        JOIN roles r ON r.id = e.role_id
        WHERE e.id = :employee_id
    )
    ORDER BY level DESC
");
$stmt->execute(['employee_id' => $_SESSION['employee_id']]);
$roles = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php includeFileWithVariables('../partials/title-meta.php', ['title' => 'Add Employee']); ?>
<?php include '../partials/head-css.php'; ?>
</head>

<body>
<div id="layout-wrapper">

<?php include '../partials/header.php'; ?>
<?php include '../partials/sidebar.php'; ?>
<?php include '../partials/horizontal.php'; ?>

<main class="app-wrapper">
<div class="container-fluid">

<?php includeFileWithVariables('../partials/page-title.php', [
    'title_sub' => 'Employees',
    'title'     => 'Create Employee'
]); ?>

<div class="row justify-content-center">
<div class="col-lg-7">

<div class="card">
<div class="card-body">

<form id="employeeForm" autocomplete="off">

<!-- ================= NAME ================= -->
<div class="row">
<div class="col-md-6 mb-3">
    <label class="form-label">First Name</label>
    <input type="text" id="first_name" class="form-control" required>
</div>
<div class="col-md-6 mb-3">
    <label class="form-label">Last Name</label>
    <input type="text" id="last_name" class="form-control" required>
</div>
</div>

<!-- ================= CONTACT ================= -->
<div class="row">
<div class="col-md-6 mb-3">
    <label class="form-label">Email</label>
    <input type="email" id="email" class="form-control" required>
</div>
<div class="col-md-6 mb-3">
    <label class="form-label">Mobile</label>
    <input type="text" id="mobile" class="form-control"
           placeholder="+91XXXXXXXXXX">
</div>
</div>

<!-- ================= SECURITY ================= -->
<div class="row">
<div class="col-md-6 mb-3">
    <label class="form-label">Password</label>
    <input type="password" id="password" class="form-control" required>
    <small class="text-muted">
        Minimum <?= PASSWORD_MIN_LENGTH ?> characters
    </small>
</div>

<div class="col-md-6 mb-3">
    <label class="form-label">Role</label>
    <select id="role_id" class="form-select" required>
        <option value="">Select Role</option>
        <?php foreach ($roles as $role): ?>
            <option value="<?= $role['id'] ?>">
                <?= htmlspecialchars($role['name']) ?>
            </option>
        <?php endforeach; ?>
    </select>
</div>
</div>

<!-- ================= STATUS ================= -->
<div class="mb-3">
    <label class="form-label">Status</label>
    <select id="status" class="form-select">
        <option value="active" selected>Active</option>
        <option value="inactive">Inactive</option>
        <option value="suspended">Suspended</option>
    </select>
</div>

<!-- ================= ACTIONS ================= -->
<div class="d-flex justify-content-end gap-2">
    <a href="<?= ADMIN_BASE_URL ?>employees/list.php"
       class="btn btn-light">
        Cancel
    </a>
    <button type="submit" class="btn btn-success">
        Create Employee
    </button>
</div>

</form>

</div>
</div>

</div>
</div>

</div>
</main>

<?php include '../partials/footer.php'; ?>
</div>

<?php include '../partials/vendor-scripts.php'; ?>

<script>
const API_CREATE = "<?= ADMIN_BASE_URL ?>api/employees/create.php";

document.getElementById('employeeForm').addEventListener('submit', function (e) {
    e.preventDefault();

    const payload = {
        first_name: document.getElementById('first_name').value.trim(),
        last_name : document.getElementById('last_name').value.trim(),
        email     : document.getElementById('email').value.trim(),
        mobile    : document.getElementById('mobile').value.trim(),
        password  : document.getElementById('password').value,
        role_id   : document.getElementById('role_id').value,
        status    : document.getElementById('status').value
    };

    fetch(API_CREATE, {
        method: 'POST',
        credentials: 'include',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
    })
    .then(res => res.json())
    .then(res => {
        if (res.status !== 'success') {
            alert(res.message || 'Employee creation failed');
            return;
        }

        window.location.href = "<?= ADMIN_BASE_URL ?>employees/list.php";
    })
    .catch(() => {
        alert('Network error. Please try again.');
    });
});
</script>

</body>
</html>
