<?php
include("../classes/manager.class.php");

$m = new Manager();
$output = '';
$name = '';
$category = '';
$status = 'active';

if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('includes/inc_head.php'); ?>
</head>
<body>
<?php include('includes/inc_top.php'); ?>
<div class="container">
    <h3>Employee Authority Setup</h3>
    <hr>

    <?php
    // Handle ADD or EDIT form submission
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        extract($_POST);
        $data = [
            'name'     => trim($name),
            'category' => $category,
            'status'   => $status
        ];

        $errors = [];

        if ($name == '') $errors[] = "Please enter employee name.";
        if ($category == '') $errors[] = "Please select category.";
        if (!in_array($status, ['active', 'inactive'])) $errors[] = "Invalid status.";

        $duplicate = EmployeeAuthoritySetup::CheckDuplicateName($name, $category, $_GET['id'] ?? 0);
        if ($duplicate) $errors[] = "This employee is already added under this category.";

        if (empty($errors)) {
            if (isset($_GET['edit'])) {
                $id = $_GET['id'];
                $q = EmployeeAuthoritySetup::UpdateEmployeeAuthority($id, $data);
            } else {
                $q = EmployeeAuthoritySetup::AddEmployeeAuthority($data);
            }

            if ($q) {
                echo "<script>window.location.href='?view&success'</script>";
            } else {
                $output .= "<div class='card orange lighten-5'><div class='card-content orange-text'>Failed to save record.</div></div>";
            }
        } else {
            foreach ($errors as $err) {
                $output .= "<div class='card orange lighten-5'><div class='card-content orange-text'>$err</div></div>";
            }
        }
    }

    // Load record for editing
    if (isset($_GET['edit'])) {
        $id = $_GET['id'];
        $record = EmployeeAuthoritySetup::GetEmployeeAuthorityById($id);
        if ($record) {
            $name = $record->name;
            $category = $record->category;
            $status = $record->status;
        }
    }

    // Display form (Add/Edit)
    if (isset($_GET['add']) || isset($_GET['edit'])) {
    ?>
        <form action="" method="post">
            <?php echo $output; ?>
            <div class="input-field">
                <input type="text" name="name" id="name" value="<?= htmlspecialchars($name) ?>" required>
                <label for="name">Employee Name *</label>
            </div>

            <div class="input-field">
                <select name="category" required>
                    <option value="" disabled <?= $category == '' ? 'selected' : '' ?>>Select Category</option>
                    <option value="issuer" <?= $category == 'issuer' ? 'selected' : '' ?>>Issuer</option>
                    <option value="approver" <?= $category == 'approver' ? 'selected' : '' ?>>Approver</option>
                </select>
                <label>Category *</label>
            </div>

            <div class="input-field">
                <select name="status" required>
                    <option value="active" <?= $status == 'active' ? 'selected' : '' ?>>Active</option>
                    <option value="inactive" <?= $status == 'inactive' ? 'selected' : '' ?>>Inactive</option>
                </select>
                <label>Status *</label>
            </div>

            <button type="submit" class="btn green">Submit</button>
            <a href="?view" class="btn red">Cancel</a>
        </form>
    <?php
    }

    // View List
    if (isset($_GET['view']) || !isset($_GET['add']) && !isset($_GET['edit'])) {
        if (isset($_GET['success'])) {
            echo "<div class='card green lighten-5'><div class='card-content green-text'>Record saved successfully.</div></div>";
        }

        $records = EmployeeAuthoritySetup::GetEmployeeAuthorityList();
    ?>
        <a href="?add" class="btn blue right">Add New</a>
        <table class="striped highlight">
            <thead>
                <tr>
                    <th>Action</th>
                    <th>Name</th>
                    <th>Category</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($records): foreach ($records as $row): ?>
                    <tr>
                        <td>
                            <a href="?edit&id=<?= $row->id ?>" class="btn-small orange">Edit</a>
                        </td>
                        <td><?= htmlspecialchars($row->name) ?></td>
                        <td><?= ucfirst($row->category) ?></td>
                        <td><?= ucfirst($row->status) ?></td>
                    </tr>
                <?php endforeach; else: ?>
                    <tr><td colspan="4">No records found.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    <?php } ?>
</div>

<?php include('includes/inc_footer.php'); ?>
<?php include('includes/inc_js.php'); ?>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        var elems = document.querySelectorAll('select');
        M.FormSelect.init(elems); // initialize Materialize select
    });
</script>
</body>
</html>
