<?php include('session.php'); include_once('admin_colonies.php'); ?>

<?php
$err = $msg = '';

$login_role = $_SESSION['role'] ?? '';
$login_division_id = $_SESSION['division_id'] ?? 0;
$login_department_id = $_SESSION['department_id'] ?? 0;

if (!in_array($login_role, array('super_admin', 'ge_admin', 'department_admin'), true)) {
    header("Location: dashboard.php");
    exit;
}

/* Edit */
$edit_id = isset($_GET['edit']) ? (int)$_GET['edit'] : 0;
$editData = null;

if ($edit_id > 0) {
    if ($login_role == 'super_admin') {
        $editQ = $conn->query("SELECT * FROM admin WHERE id='$edit_id' AND status='1' LIMIT 1");
    } elseif ($login_role == 'department_admin') {
        $editQ = $conn->query("
            SELECT * FROM admin
            WHERE id='$edit_id'
            AND status='1'
            AND role IN ('je', 'contractor')
            AND department_id='$login_department_id'
            LIMIT 1
        ");
    } else {
        $editQ = $conn->query("
            SELECT * FROM admin 
            WHERE id='$edit_id'
            AND status='1'
            AND role IN ('department_admin', 'je', 'contractor')
            AND division_id='$login_division_id'
            LIMIT 1
        ");
    }

    if ($editQ && $editQ->num_rows > 0) {
        $editData = $editQ->fetch_assoc();
    }
}

/* Delete */
if (isset($_GET['delete'])) {
    $delete_id = (int)$_GET['delete'];

    if ($login_role == 'super_admin') {
        $delete = $conn->query("UPDATE admin SET status='0' WHERE id='$delete_id'");
    } elseif ($login_role == 'department_admin') {
        $delete = $conn->query("
            UPDATE admin SET status='0'
            WHERE id='$delete_id'
            AND role IN ('je', 'contractor')
            AND department_id='$login_department_id'
        ");
    } else {
        $delete = $conn->query("
            UPDATE admin SET status='0'
            WHERE id='$delete_id'
            AND role IN ('department_admin', 'je', 'contractor')
            AND division_id='$login_division_id'
        ");
    }

    if ($delete) {
        $msg = "Admin deleted successfully.";
    } else {
        $err = $conn->error;
    }
}

/* Add / Update */
if (isset($_POST['submit'])) {

    $admin_id = isset($_POST['admin_id']) ? (int)$_POST['admin_id'] : 0;

    $name     = mysqli_real_escape_string($conn, $_POST['name']);
    $mobile   = mysqli_real_escape_string($conn, $_POST['mobile']);
    $password = mysqli_real_escape_string($conn, $_POST['password']);

    if ($login_role == 'super_admin') {
        $role = mysqli_real_escape_string($conn, $_POST['role']);
        $division_id = !empty($_POST['division_id']) ? (int)$_POST['division_id'] : 'NULL';
        $department_id = !empty($_POST['department_id']) ? (int)$_POST['department_id'] : 'NULL';
    } elseif ($login_role == 'department_admin') {
        $role = mysqli_real_escape_string($conn, $_POST['role'] ?? 'je');
        if(!in_array($role, array('je', 'contractor'), true)) {
            $role = 'je';
        }
        $division_id = (int)$login_division_id;
        $department_id = $role === 'je' ? (int)$login_department_id : (!empty($_POST['department_id']) ? (int)$_POST['department_id'] : 'NULL');
    } else {
        $role = mysqli_real_escape_string($conn, $_POST['role']);
        if (!in_array($role, array('department_admin', 'contractor'), true)) {
            $role = 'department_admin';
        }
        $division_id = (int)$login_division_id;
        $department_id = !empty($_POST['department_id']) ? (int)$_POST['department_id'] : 'NULL';
    }

    if ($role == 'super_admin') {
        $division_id = 'NULL';
        $department_id = 'NULL';
        $type = 'super';
        $designation = 'Super Admin';
    } elseif ($role == 'ge_admin') {
        $department_id = 'NULL';
        $type = 'ge_admin';
        $designation = 'GE Admin';
    } elseif ($role == 'bso') {
        $department_id = 'NULL';
        $type = 'bso';
        $designation = 'BSO';
    } elseif ($role == 'je') {
        $type = 'dept';
        $designation = 'JE';
    } elseif ($role == 'contractor') {
        $type = 'contractor';
        $designation = 'Contractor';
    } else {
        $type = 'department_admin';
        $designation = 'Department Admin';
    }

    if (in_array($role, array('ge_admin', 'bso', 'department_admin', 'je', 'contractor'), true) && $division_id === 'NULL') {
        $err = "Please select division.";
    }

    if (in_array($role, array('department_admin', 'je'), true) && $department_id === 'NULL') {
        $err = "Please select department.";
    }
    if (in_array($role, array('department_admin', 'je', 'contractor'), true) && empty($_POST['colony_ids'])) {
        $err = "Please assign at least one locality / RWA.";
    }
    if(in_array($role, array('department_admin', 'je', 'contractor'), true) && $department_id !== 'NULL') {
        $validDepartment = $conn->query("
            SELECT id FROM departments
            WHERE id='".(int)$department_id."'
              AND division_id='".(int)$division_id."'
              AND status='1'
            LIMIT 1
        ");
        if(!$validDepartment || $validDepartment->num_rows === 0) {
            $err = "Selected department does not belong to this division.";
        }
    }

    if ($admin_id > 0) {
        if ($login_role == 'ge_admin') {
            $check = $conn->query("
                SELECT id FROM admin
                WHERE id='$admin_id'
                AND role IN ('department_admin', 'je', 'contractor')
                AND division_id='$login_division_id'
                LIMIT 1
            ");

            if (!$check || $check->num_rows == 0) {
                $err = "You are not allowed to update this admin.";
            }
        } elseif ($login_role == 'department_admin') {
            $check = $conn->query("
                SELECT id FROM admin
                WHERE id='$admin_id'
                AND role IN ('je', 'contractor')
                AND department_id='$login_department_id'
                LIMIT 1
            ");

            if (!$check || $check->num_rows == 0) {
                $err = "You are not allowed to update this contractor.";
            }
        }

        if (empty($err)) {
            $sql = "UPDATE admin SET
                    name='$name',
                    mobile='$mobile',
                    password='$password',
                    role='$role',
                    type='$type',
                    designation='$designation',
                    division_id=$division_id,
                    department_id=$department_id
                    WHERE id='$admin_id'";
        }

    } else {
        $sql = "INSERT INTO admin
                (name, mobile, password, role, type, designation, division_id, department_id, status)
                VALUES
                ('$name', '$mobile', '$password', '$role', '$type', '$designation', $division_id, $department_id, '1')";
    }

    if (empty($err)) {
        if ($conn->query($sql)) {
            $savedAdminId = $admin_id > 0 ? $admin_id : (int)$conn->insert_id;
            if(in_array($role, array('department_admin', 'je', 'contractor'), true)) {
                $colonyIds = $_POST['colony_ids'] ?? array();
                if($login_role === 'department_admin') {
                    $colonyIds = array_values(array_intersect(
                        array_map('intval', $colonyIds),
                        admin_colony_ids($conn, (int)$_SESSION['admin'])
                    ));
                }
                save_admin_colonies(
                    $conn,
                    $savedAdminId,
                    $colonyIds,
                    (int)$division_id,
                    (int)$department_id
                );
            } else {
                $conn->query("DELETE FROM admin_colonies WHERE admin_id='".$savedAdminId."'");
            }
            $msg = ($admin_id > 0) ? "Admin updated successfully." : "Admin added successfully.";
            $editData = null;
            $edit_id = 0;
        } else {
            $err = $conn->error;
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>ECIMS ADMIN | Manage Admin Users</title>
    <?php include('includes/head.php'); ?>

    <style>
        th, td {
            text-align: center;
            vertical-align: middle;
        }
    </style>
</head>

<body>
<div class="container-scroller">

    <div class="horizontal-menu">
        <?php include('includes/header.php'); ?>
    </div>

    <div class="container-fluid page-body-wrapper">
        <div class="main-panel">

            <div class="content-wrapper">

                <div class="page-header">
                    <h3 class="page-title">Manage Admin Users</h3>
                </div>

                <?php if (!empty($err)) { ?>
                    <div class="alert alert-danger">
                        <strong>Error!</strong> <?php echo $err; ?>
                    </div>
                <?php } ?>

                <?php if (!empty($msg)) { ?>
                    <div class="alert alert-success">
                        <strong>Success!</strong> <?php echo $msg; ?>
                    </div>
                <?php } ?>

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

                        <h4 class="card-title">
                            <?php echo $editData ? 'Edit Admin User' : 'Add Admin User'; ?>
                        </h4>

                        <form method="POST">

                            <input type="hidden" name="admin_id" value="<?php echo $editData['id'] ?? ''; ?>">

                            <div class="row">

                                <div class="col-md-4 form-group">
                                    <label>Name</label>
                                    <input type="text" name="name" required class="form-control"
                                           value="<?php echo $editData['name'] ?? ''; ?>">
                                </div>

                                <div class="col-md-4 form-group">
                                    <label>Mobile</label>
                                    <input type="text" name="mobile" required class="form-control"
                                           value="<?php echo $editData['mobile'] ?? ''; ?>">
                                </div>

                                <div class="col-md-4 form-group">
                                    <label>Password</label>
                                    <input type="text" name="password" required class="form-control"
                                           value="<?php echo $editData['password'] ?? ''; ?>">
                                </div>

                                <div class="col-md-4 form-group">
                                    <label>Admin Role</label>

                                    <?php if ($login_role == 'department_admin') { ?>

                                        <select name="role" id="role" required class="form-control" onchange="toggleFields()">
                                            <option value="je" <?php echo (($editData['role'] ?? '') == 'je') ? 'selected' : ''; ?>>JE</option>
                                            <option value="contractor" <?php echo (($editData['role'] ?? '') == 'contractor') ? 'selected' : ''; ?>>Contractor</option>
                                        </select>

                                    <?php } elseif ($login_role == 'ge_admin') { ?>

                                        <select name="role" id="role" required class="form-control" onchange="toggleFields()">
                                            <option value="department_admin" <?php echo (($editData['role'] ?? '') == 'department_admin') ? 'selected' : ''; ?>>AGE Admin</option>
                                            <option value="contractor" <?php echo (($editData['role'] ?? '') == 'contractor') ? 'selected' : ''; ?>>Contractor</option>
                                        </select>

                                    <?php } else { ?>

                                        <select name="role" id="role" required class="form-control" onchange="toggleFields()">
                                            <option value="">Select Role</option>

                                            <option value="super_admin"
                                                <?php echo (($editData['role'] ?? '') == 'super_admin') ? 'selected' : ''; ?>>
                                                Super Admin
                                            </option>

                                            <option value="ge_admin"
                                                <?php echo (($editData['role'] ?? '') == 'ge_admin') ? 'selected' : ''; ?>>
                                                GE Master Admin
                                            </option>

                                            <option value="department_admin"
                                                <?php echo (($editData['role'] ?? '') == 'department_admin') ? 'selected' : ''; ?>>
                                                AGE Admin
                                            </option>

                                            <option value="bso"
                                                <?php echo (($editData['role'] ?? '') == 'bso') ? 'selected' : ''; ?>>
                                                BSO
                                            </option>

                                            <option value="je"
                                                <?php echo (($editData['role'] ?? '') == 'je') ? 'selected' : ''; ?>>
                                                JE
                                            </option>

                                            <option value="contractor"
                                                <?php echo (($editData['role'] ?? '') == 'contractor') ? 'selected' : ''; ?>>
                                                Contractor
                                            </option>
                                        </select>

                                    <?php } ?>
                                </div>

                                <div class="col-md-4 form-group" id="divisionBox">
                                    <label>Division</label>

                                    <?php if ($login_role == 'department_admin') { ?>

                                        <?php
                                        $deptDivName = '';
                                        $deptDiv = $conn->query("SELECT name FROM divisions WHERE id='$login_division_id' LIMIT 1");
                                        if ($deptDiv && $deptDiv->num_rows > 0) {
                                            $deptDivName = $deptDiv->fetch_assoc()['name'];
                                        }
                                        ?>

                                        <input type="hidden" name="division_id" id="division_id" value="<?php echo $login_division_id; ?>">
                                        <input type="text" class="form-control" value="<?php echo $deptDivName; ?>" readonly>

                                    <?php } elseif ($login_role == 'ge_admin') { ?>

                                        <?php
                                        $geDivName = '';
                                        $geDiv = $conn->query("SELECT name FROM divisions WHERE id='$login_division_id' LIMIT 1");
                                        if ($geDiv && $geDiv->num_rows > 0) {
                                            $geDivName = $geDiv->fetch_assoc()['name'];
                                        }
                                        ?>

                                        <input type="hidden" name="division_id" id="division_id" value="<?php echo $login_division_id; ?>">
                                        <input type="text" class="form-control" value="<?php echo $geDivName; ?>" readonly>

                                    <?php } else { ?>

                                        <select name="division_id" id="division_id" class="form-control">
                                            <option value="">Select Division</option>

                                            <?php
                                            $divisionsQ = $conn->query("SELECT * FROM divisions WHERE status='1' ORDER BY name ASC");
                                            while ($div = $divisionsQ->fetch_assoc()) {
                                            ?>
                                                <option value="<?php echo $div['id']; ?>"
                                                    <?php echo (($editData['division_id'] ?? '') == $div['id']) ? 'selected' : ''; ?>>
                                                    <?php echo $div['name']; ?>
                                                </option>
                                            <?php } ?>
                                        </select>

                                    <?php } ?>
                                </div>

                                <div class="col-md-4 form-group" id="departmentBox">
                                    <label>Department</label>

                                    <select name="department_id" id="department_id" class="form-control">
                                        <option value="">Select Department</option>

                                        <?php
	                                        if ($login_role == 'department_admin') {
	                                            $departmentsQ = $conn->query("
	                                                SELECT * FROM departments
	                                                WHERE status='1'
	                                                AND id='$login_department_id'
	                                                ORDER BY name ASC
	                                            ");
	                                        } elseif ($login_role == 'ge_admin') {
                                            $departmentsQ = $conn->query("
                                                SELECT * FROM departments
                                                WHERE status='1'
                                                AND division_id='$login_division_id'
                                                ORDER BY name ASC
                                            ");
                                        } else {
                                            $departmentsQ = $conn->query("
                                                SELECT * FROM departments
                                                WHERE status='1'
                                                ORDER BY name ASC
                                            ");
                                        }

                                        while ($dep = $departmentsQ->fetch_assoc()) {
                                        ?>
                                            <option value="<?php echo $dep['id']; ?>"
                                                    data-division="<?php echo $dep['division_id']; ?>"
                                                <?php echo (($editData['department_id'] ?? '') == $dep['id']) ? 'selected' : ''; ?>>
                                                <?php echo $dep['name']; ?>
                                            </option>
                                        <?php } ?>
                                    </select>
                                </div>

                                <div class="col-md-8 form-group" id="colonyBox">
                                    <label>Assigned Locality / RWA</label>
                                    <?php $selectedColonies = $editData ? admin_colony_ids($conn, $editData['id']) : array(); ?>
                                    <select name="colony_ids[]" id="colony_ids" class="form-control" multiple>
                                        <?php
                                        $colonyWhere = "status='1'";
                                        if($login_role === 'ge_admin' || $login_role === 'department_admin') {
                                            $colonyWhere .= " AND division_id='".(int)$login_division_id."'";
                                        }
                                        if($login_role === 'department_admin') {
                                            $allowedColonies = admin_colony_ids($conn, (int)$_SESSION['admin']);
                                            $colonyWhere .= $allowedColonies
                                                ? " AND id IN (".implode(',', $allowedColonies).")"
                                                : " AND 1=0";
                                        }
                                        $coloniesQ = $conn->query("SELECT * FROM colonies WHERE ".$colonyWhere." ORDER BY name ASC");
                                        while($colony = $coloniesQ->fetch_assoc()) {
                                        ?>
                                            <option value="<?php echo $colony['id']; ?>"
                                                    data-division="<?php echo $colony['division_id']; ?>"
                                                    data-department="<?php echo $colony['department_id']; ?>"
                                                <?php echo in_array((int)$colony['id'], $selectedColonies, true) ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($colony['name']); ?>
                                            </option>
                                        <?php } ?>
                                    </select>
                                    <small class="text-muted">Only complaints from selected localities will be visible to this login.</small>
                                </div>

                            </div>

                            <button type="submit" name="submit" class="btn btn-primary">
                                <?php echo $editData ? 'Update' : 'Submit'; ?>
                            </button>

                            <?php if ($editData) { ?>
	                                <a href="addSuper.php" class="btn btn-light">Cancel</a>
                            <?php } ?>

                        </form>

                    </div>
                </div>

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

                        <h4 class="card-title">All Admin Users</h4>

                        <div class="table-responsive">
                            <table class="table table-striped table-bordered">
                                <thead>
                                <tr>
                                    <th>Sr No.</th>
                                    <th>Name</th>
                                    <th>Mobile</th>
                                    <th>Password</th>
                                    <th>Role</th>
                                    <th>Division</th>
                                    <th>Department</th>
                                    <th>Locality / RWA</th>
                                    <th>Action</th>
                                </tr>
                                </thead>

                                <tbody>

                                <?php
                                $count = 0;

                                if ($login_role == 'super_admin') {

                                    $admins = $conn->query("
                                        SELECT a.*,
                                               d.name AS division_name,
                                               dep.name AS department_name
                                        FROM admin a
                                        LEFT JOIN divisions d ON d.id = a.division_id
                                        LEFT JOIN departments dep ON dep.id = a.department_id
                                        WHERE a.status='1'
                                        ORDER BY a.id DESC
                                    ");

	                                } elseif ($login_role == 'department_admin') {

	                                    $admins = $conn->query("
	                                        SELECT a.*,
	                                               d.name AS division_name,
	                                               dep.name AS department_name
	                                        FROM admin a
	                                        LEFT JOIN divisions d ON d.id = a.division_id
	                                        LEFT JOIN departments dep ON dep.id = a.department_id
	                                        WHERE a.status='1'
	                                        AND a.role IN ('je', 'contractor')
	                                        AND a.department_id='$login_department_id'
	                                        ORDER BY a.id DESC
	                                    ");

	                                } else {

                                    $admins = $conn->query("
                                        SELECT a.*,
                                               d.name AS division_name,
                                               dep.name AS department_name
                                        FROM admin a
                                        LEFT JOIN divisions d ON d.id = a.division_id
                                        LEFT JOIN departments dep ON dep.id = a.department_id
                                        WHERE a.status='1'
	                                        AND a.role IN ('department_admin', 'je', 'contractor')
                                        AND a.division_id='$login_division_id'
                                        ORDER BY a.id DESC
                                    ");
                                }

                                if ($admins && $admins->num_rows > 0) {
                                    while ($row = $admins->fetch_assoc()) {
                                        $count++;
                                ?>

                                    <tr>
                                        <td><?php echo $count; ?></td>
                                        <td><?php echo $row['name']; ?></td>
                                        <td><?php echo $row['mobile']; ?></td>
                                        <td><?php echo $row['password']; ?></td>
                                        <td><?php echo ucwords(str_replace('_', ' ', $row['role'])); ?></td>
                                        <td><?php echo $row['division_name'] ?: '-'; ?></td>
                                        <td><?php echo $row['department_name'] ?: '-'; ?></td>
                                        <td>
                                            <?php
                                            $rowColonies = admin_colony_ids($conn, $row['id']);
                                            if($rowColonies) {
                                                $colonyNames = $conn->query("SELECT name FROM colonies WHERE id IN (".implode(',', $rowColonies).") ORDER BY name");
                                                $names = array();
                                                while($colonyRow = $colonyNames->fetch_assoc()) {
                                                    $names[] = $colonyRow['name'];
                                                }
                                                echo htmlspecialchars(implode(', ', $names));
                                            } else {
                                                echo '-';
                                            }
                                            ?>
                                        </td>

                                        <td>
	                                            <a href="addSuper.php?edit=<?php echo $row['id']; ?>"
                                               class="btn btn-xs btn-outline-primary">
                                                Edit
                                            </a>

	                                            <a href="addSuper.php?delete=<?php echo $row['id']; ?>"
                                               onclick="return confirm('Are you sure?')"
                                               class="btn btn-xs btn-outline-danger">
                                                Delete
                                            </a>
                                        </td>
                                    </tr>

                                <?php } } else { ?>

                                    <tr>
                                        <td colspan="9">No Records Found!</td>
                                    </tr>

                                <?php } ?>

                                </tbody>
                            </table>
                        </div>

                    </div>
                </div>

            </div>

            <?php include('includes/footer.php'); ?>

        </div>
    </div>
</div>

<?php include('includes/foot.php'); ?>

<script>
function toggleFields() {
    var roleField = document.getElementById('role');
    var role = roleField ? roleField.value : 'department_admin';

    var divisionBox = document.getElementById('divisionBox');
    var departmentBox = document.getElementById('departmentBox');
    var colonyBox = document.getElementById('colonyBox');

    var division = document.getElementById('division_id');
    var department = document.getElementById('department_id');

    if (role === 'super_admin') {
        if (divisionBox) divisionBox.style.display = 'none';
        if (departmentBox) departmentBox.style.display = 'none';
        if (colonyBox) colonyBox.style.display = 'none';

        if (division) division.value = '';
        if (department) department.value = '';
    }

    else if (role === 'ge_admin' || role === 'bso') {
        if (divisionBox) divisionBox.style.display = 'block';
        if (departmentBox) departmentBox.style.display = 'none';
        if (colonyBox) colonyBox.style.display = 'none';

        if (department) department.value = '';
    }

    else if (role === 'department_admin' || role === 'je' || role === 'contractor') {
        if (divisionBox) divisionBox.style.display = 'block';
        if (departmentBox) departmentBox.style.display = 'block';
        if (colonyBox) colonyBox.style.display = 'block';
    }

    else {
        if (divisionBox) divisionBox.style.display = 'none';
        if (departmentBox) departmentBox.style.display = 'none';
        if (colonyBox) colonyBox.style.display = 'none';
    }

    filterDepartments();
    filterColonies();
}

function filterDepartments() {
    var division = document.getElementById('division_id');
    var department = document.getElementById('department_id');

    if (!division || !department) return;

    var selectedDivision = division.value;
    var options = department.options;

    for (var i = 0; i < options.length; i++) {
        var divId = options[i].getAttribute('data-division');

        if (!divId || divId === selectedDivision) {
            options[i].style.display = 'block';
        } else {
            options[i].style.display = 'none';
        }
    }
}

function filterColonies() {
    var division = document.getElementById('division_id');
    var colonies = document.getElementById('colony_ids');
    if (!division || !colonies) return;

    var selectedDivision = division.value;
    for (var i = 0; i < colonies.options.length; i++) {
        var option = colonies.options[i];
        var visible = !selectedDivision || option.getAttribute('data-division') === selectedDivision;
        option.style.display = visible ? 'block' : 'none';
        if (!visible) option.selected = false;
    }
}

var divisionSelect = document.getElementById('division_id');

if (divisionSelect) {
    divisionSelect.addEventListener('change', function () {
        var department = document.getElementById('department_id');
        if (department) department.value = '';
        filterDepartments();
        filterColonies();
    });
}

toggleFields();
filterDepartments();
filterColonies();
</script>

</body>
</html>
