<?php
// /elms/admin/lecturers/index.php
declare(strict_types=1);

$PAGE_TITLE = 'Lecturers';
$ACTIVE = 'lecturers';

require_once __DIR__ . '/../../includes/admin_auth.php';
require_once __DIR__ . '/../../includes/db.php';

$helpers = __DIR__ . '/../../includes/helpers.php';
if (is_file($helpers)) {
    require_once $helpers;
}

if (!isset($mysqli) && isset($conn)) {
    $mysqli = $conn;
}

$db = null;
if (isset($mysqli) && $mysqli instanceof mysqli) {
    $db = $mysqli;
} elseif (isset($conn) && $conn instanceof mysqli) {
    $db = $conn;
}

require_once __DIR__ . '/../../includes/admin_layout_top.php';

if (!function_exists('esc')) {
    function esc($s): string
    {
        return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

if (!function_exists('admin_table_exists')) {
    function admin_table_exists(mysqli $db, string $table): bool
    {
        $safe = $db->real_escape_string($table);
        $res = $db->query("SHOW TABLES LIKE '{$safe}'");
        return $res && $res->num_rows > 0;
    }
}

if (!function_exists('admin_column_exists')) {
    function admin_column_exists(mysqli $db, string $table, string $column): bool
    {
        $safeTable = $db->real_escape_string($table);
        $safeCol   = $db->real_escape_string($column);
        $res = $db->query("SHOW COLUMNS FROM `{$safeTable}` LIKE '{$safeCol}'");
        return $res && $res->num_rows > 0;
    }
}

if (!$db) {
    echo '<div class="alert alert-danger">Database connection not found.</div>';
    require_once __DIR__ . '/../../includes/admin_layout_bottom.php';
    exit;
}

if (!admin_table_exists($db, 'elms_users')) {
    echo '<div class="alert alert-warning">elms_users table not found.</div>';
    require_once __DIR__ . '/../../includes/admin_layout_bottom.php';
    exit;
}

$msg = '';
$err = '';

$hasRoleSlug = admin_column_exists($db, 'elms_users', 'role_slug');
$hasRole     = admin_column_exists($db, 'elms_users', 'role');
$hasRoleCode = admin_column_exists($db, 'elms_users', 'role_code');

$roleWhereParts = [];
if ($hasRoleSlug) $roleWhereParts[] = "role_slug = 'lecturer'";
if ($hasRole)     $roleWhereParts[] = "role = 'lecturer'";
if ($hasRoleCode) $roleWhereParts[] = "role_code = 'lecturer'";

$roleWhereSql = $roleWhereParts ? '(' . implode(' OR ', $roleWhereParts) . ')' : '1=1';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'create') {
        $fullName = trim((string)($_POST['full_name'] ?? ''));
        $username = trim((string)($_POST['username'] ?? ''));
        $email    = trim((string)($_POST['email'] ?? ''));
        $password = trim((string)($_POST['password'] ?? ''));

        if ($fullName === '') {
            $err = 'Lecturer name is required.';
        } elseif ($username === '') {
            $err = 'Username is required.';
        } elseif ($password === '') {
            $err = 'Password is required.';
        } else {
            $dupSql = "SELECT id FROM elms_users WHERE username = ?";
            $dupTypes = 's';
            $dupParams = [$username];

            if ($email !== '' && admin_column_exists($db, 'elms_users', 'email')) {
                $dupSql .= " OR email = ?";
                $dupTypes .= 's';
                $dupParams[] = $email;
            }

            $dup = $db->prepare($dupSql);
            $dup->bind_param($dupTypes, ...$dupParams);
            $dup->execute();
            $dupRes = $dup->get_result();
            $alreadyExists = $dupRes && $dupRes->num_rows > 0;
            $dup->close();

            if ($alreadyExists) {
                $err = 'Username or email already exists.';
            } else {
                $cols = [];
                $vals = [];
                $types = '';

                if (admin_column_exists($db, 'elms_users', 'username')) {
                    $cols[] = 'username';
                    $vals[] = $username;
                    $types .= 's';
                }

                if (admin_column_exists($db, 'elms_users', 'password_hash')) {
                    $cols[] = 'password_hash';
                    $vals[] = password_hash($password, PASSWORD_DEFAULT);
                    $types .= 's';
                } elseif (admin_column_exists($db, 'elms_users', 'password')) {
                    $cols[] = 'password';
                    $vals[] = password_hash($password, PASSWORD_DEFAULT);
                    $types .= 's';
                }

                if ($hasRoleSlug) {
                    $cols[] = 'role_slug';
                    $vals[] = 'lecturer';
                    $types .= 's';
                }

                if ($hasRole) {
                    $cols[] = 'role';
                    $vals[] = 'lecturer';
                    $types .= 's';
                }

                if ($hasRoleCode) {
                    $cols[] = 'role_code';
                    $vals[] = 'lecturer';
                    $types .= 's';
                }

                if (admin_column_exists($db, 'elms_users', 'email')) {
                    $cols[] = 'email';
                    $vals[] = $email;
                    $types .= 's';
                }

                if (admin_column_exists($db, 'elms_users', 'full_name')) {
                    $cols[] = 'full_name';
                    $vals[] = $fullName;
                    $types .= 's';
                } elseif (admin_column_exists($db, 'elms_users', 'name')) {
                    $cols[] = 'name';
                    $vals[] = $fullName;
                    $types .= 's';
                }

                if (admin_column_exists($db, 'elms_users', 'is_active')) {
                    $cols[] = 'is_active';
                    $vals[] = 1;
                    $types .= 'i';
                } elseif (admin_column_exists($db, 'elms_users', 'status')) {
                    $cols[] = 'status';
                    $vals[] = 'active';
                    $types .= 's';
                }

                if (admin_column_exists($db, 'elms_users', 'created_at')) {
                    $cols[] = 'created_at';
                    $vals[] = date('Y-m-d H:i:s');
                    $types .= 's';
                }

                if (!$cols) {
                    $err = 'No supported columns found in elms_users table.';
                } else {
                    $placeholders = implode(',', array_fill(0, count($cols), '?'));
                    $colSql = '`' . implode('`,`', $cols) . '`';

                    $stmt = $db->prepare("INSERT INTO elms_users ({$colSql}) VALUES ({$placeholders})");

                    if (!$stmt) {
                        $err = 'Create prepare failed: ' . $db->error;
                    } else {
                        $stmt->bind_param($types, ...$vals);

                        if ($stmt->execute()) {
                            $msg = 'Lecturer created successfully.';
                        } else {
                            $err = 'Lecturer create failed: ' . $stmt->error;
                        }

                        $stmt->close();
                    }
                }
            }
        }
    }

    if ($action === 'update') {
        $id       = (int)($_POST['id'] ?? 0);
        $fullName = trim((string)($_POST['full_name'] ?? ''));
        $username = trim((string)($_POST['username'] ?? ''));
        $email    = trim((string)($_POST['email'] ?? ''));
        $password = trim((string)($_POST['password'] ?? ''));

        if ($id <= 0) {
            $err = 'Invalid lecturer.';
        } elseif ($fullName === '') {
            $err = 'Lecturer name is required.';
        } elseif ($username === '') {
            $err = 'Username is required.';
        } else {
            $dupSql = "SELECT id FROM elms_users WHERE id <> ? AND username = ?";
            $dupTypes = 'is';
            $dupParams = [$id, $username];

            if ($email !== '' && admin_column_exists($db, 'elms_users', 'email')) {
                $dupSql .= " OR (id <> ? AND email = ?)";
                $dupTypes .= 'is';
                $dupParams[] = $id;
                $dupParams[] = $email;
            }

            $dup = $db->prepare($dupSql);
            $dup->bind_param($dupTypes, ...$dupParams);
            $dup->execute();
            $dupRes = $dup->get_result();
            $alreadyExists = $dupRes && $dupRes->num_rows > 0;
            $dup->close();

            if ($alreadyExists) {
                $err = 'Username or email already exists.';
            } else {
                $set = [];
                $vals = [];
                $types = '';

                if (admin_column_exists($db, 'elms_users', 'username')) {
                    $set[] = 'username = ?';
                    $vals[] = $username;
                    $types .= 's';
                }

                if (admin_column_exists($db, 'elms_users', 'email')) {
                    $set[] = 'email = ?';
                    $vals[] = $email;
                    $types .= 's';
                }

                if (admin_column_exists($db, 'elms_users', 'full_name')) {
                    $set[] = 'full_name = ?';
                    $vals[] = $fullName;
                    $types .= 's';
                } elseif (admin_column_exists($db, 'elms_users', 'name')) {
                    $set[] = 'name = ?';
                    $vals[] = $fullName;
                    $types .= 's';
                }

                if ($password !== '') {
                    if (admin_column_exists($db, 'elms_users', 'password_hash')) {
                        $set[] = 'password_hash = ?';
                        $vals[] = password_hash($password, PASSWORD_DEFAULT);
                        $types .= 's';
                    } elseif (admin_column_exists($db, 'elms_users', 'password')) {
                        $set[] = 'password = ?';
                        $vals[] = password_hash($password, PASSWORD_DEFAULT);
                        $types .= 's';
                    }
                }

                if (!$set) {
                    $err = 'No editable columns found.';
                } else {
                    $vals[] = $id;
                    $types .= 'i';

                    $stmt = $db->prepare("
                        UPDATE elms_users
                        SET " . implode(', ', $set) . "
                        WHERE id = ?
                          AND {$roleWhereSql}
                        LIMIT 1
                    ");

                    if ($stmt) {
                        $stmt->bind_param($types, ...$vals);

                        if ($stmt->execute()) {
                            $msg = 'Lecturer updated successfully.';
                        } else {
                            $err = 'Lecturer update failed: ' . $stmt->error;
                        }

                        $stmt->close();
                    } else {
                        $err = 'Update prepare failed: ' . $db->error;
                    }
                }
            }
        }
    }

    if ($action === 'toggle_status') {
        $id = (int)($_POST['id'] ?? 0);

        if ($id > 0) {
            if (admin_column_exists($db, 'elms_users', 'is_active')) {
                $stmt = $db->prepare("
                    UPDATE elms_users
                    SET is_active = CASE WHEN is_active = 1 THEN 0 ELSE 1 END
                    WHERE id = ?
                      AND {$roleWhereSql}
                    LIMIT 1
                ");
                $stmt->bind_param('i', $id);
            } elseif (admin_column_exists($db, 'elms_users', 'status')) {
                $stmt = $db->prepare("
                    UPDATE elms_users
                    SET status = CASE WHEN LOWER(status) = 'active' THEN 'inactive' ELSE 'active' END
                    WHERE id = ?
                      AND {$roleWhereSql}
                    LIMIT 1
                ");
                $stmt->bind_param('i', $id);
            } else {
                $stmt = null;
            }

            if ($stmt) {
                if ($stmt->execute()) {
                    $msg = 'Lecturer status updated.';
                } else {
                    $err = 'Status update failed.';
                }
                $stmt->close();
            }
        }
    }

    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);

        if ($id > 0) {
            $stmt = $db->prepare("
                DELETE FROM elms_users
                WHERE id = ?
                  AND {$roleWhereSql}
                LIMIT 1
            ");

            if ($stmt) {
                $stmt->bind_param('i', $id);

                if ($stmt->execute()) {
                    $msg = 'Lecturer deleted successfully.';
                } else {
                    $err = 'Lecturer delete failed: ' . $stmt->error;
                }

                $stmt->close();
            } else {
                $err = 'Delete prepare failed: ' . $db->error;
            }
        }
    }
}

$q = trim((string)($_GET['q'] ?? ''));

$rows = [];

$select = [];
$select[] = 'id';
$select[] = admin_column_exists($db, 'elms_users', 'username') ? 'username' : "'' AS username";
$select[] = admin_column_exists($db, 'elms_users', 'email') ? 'email' : "'' AS email";

if (admin_column_exists($db, 'elms_users', 'full_name')) {
    $select[] = 'full_name';
} elseif (admin_column_exists($db, 'elms_users', 'name')) {
    $select[] = 'name AS full_name';
} else {
    $select[] = "'' AS full_name";
}

if (admin_column_exists($db, 'elms_users', 'is_active')) {
    $select[] = 'is_active';
} elseif (admin_column_exists($db, 'elms_users', 'status')) {
    $select[] = "CASE WHEN LOWER(status) = 'active' THEN 1 ELSE 0 END AS is_active";
} else {
    $select[] = '1 AS is_active';
}

if (admin_column_exists($db, 'elms_users', 'created_at')) {
    $select[] = 'created_at';
} else {
    $select[] = 'NULL AS created_at';
}

$where = [];
$where[] = $roleWhereSql;

$types = '';
$params = [];

if ($q !== '') {
    $search = [];

    if (admin_column_exists($db, 'elms_users', 'full_name')) {
        $search[] = 'full_name LIKE ?';
        $params[] = '%' . $q . '%';
        $types .= 's';
    }

    if (admin_column_exists($db, 'elms_users', 'name')) {
        $search[] = 'name LIKE ?';
        $params[] = '%' . $q . '%';
        $types .= 's';
    }

    if (admin_column_exists($db, 'elms_users', 'username')) {
        $search[] = 'username LIKE ?';
        $params[] = '%' . $q . '%';
        $types .= 's';
    }

    if (admin_column_exists($db, 'elms_users', 'email')) {
        $search[] = 'email LIKE ?';
        $params[] = '%' . $q . '%';
        $types .= 's';
    }

    if ($search) {
        $where[] = '(' . implode(' OR ', $search) . ')';
    }
}

$sql = "
    SELECT " . implode(', ', $select) . "
    FROM elms_users
    WHERE " . implode(' AND ', $where) . "
    ORDER BY full_name ASC, id DESC
";

$stmt = $db->prepare($sql);

if ($stmt) {
    if ($types !== '' && $params) {
        $stmt->bind_param($types, ...$params);
    }

    $stmt->execute();
    $res = $stmt->get_result();

    if ($res) {
        $rows = $res->fetch_all(MYSQLI_ASSOC);
    }

    $stmt->close();
}
?>

<div class="admin-card mb-4">
    <div class="admin-card-header">
        <div>
            <h5 class="mb-0">Lecturers</h5>
            <div class="text-muted small">Create and manage lecturer accounts</div>
        </div>

        <div class="d-flex flex-wrap gap-2">
            <form method="get" class="d-flex gap-2">
                <input
                    type="text"
                    name="q"
                    class="form-control"
                    placeholder="Search lecturer..."
                    value="<?= esc($q) ?>"
                    style="min-width:240px;"
                >

                <button class="btn btn-outline-primary">
                    <i class="bi bi-search me-1"></i>
                    Search
                </button>

                <?php if ($q !== ''): ?>
                    <a href="index.php" class="btn btn-outline-secondary">Reset</a>
                <?php endif; ?>
            </form>

            <button class="btn btn-admin-primary" data-bs-toggle="modal" data-bs-target="#addLecturerModal">
                <i class="bi bi-plus-circle me-1"></i>
                Add Lecturer
            </button>
        </div>
    </div>

    <div class="admin-card-body">
        <?php if ($msg): ?>
            <div class="alert alert-success"><?= esc($msg) ?></div>
        <?php endif; ?>

        <?php if ($err): ?>
            <div class="alert alert-danger"><?= esc($err) ?></div>
        <?php endif; ?>

        <div class="row g-3">
            <div class="col-md-4">
                <div class="border rounded-4 p-3 bg-light h-100">
                    <div class="text-muted small fw-semibold">Total Lecturers</div>
                    <div class="fs-3 fw-bold"><?= number_format(count($rows)) ?></div>
                </div>
            </div>

            <div class="col-md-4">
                <div class="border rounded-4 p-3 bg-light h-100">
                    <div class="text-muted small fw-semibold">Active</div>
                    <div class="fs-3 fw-bold text-success">
                        <?= number_format(count(array_filter($rows, fn($r) => (int)($r['is_active'] ?? 1) === 1))) ?>
                    </div>
                </div>
            </div>

            <div class="col-md-4">
                <div class="border rounded-4 p-3 bg-light h-100">
                    <div class="text-muted small fw-semibold">Inactive</div>
                    <div class="fs-3 fw-bold text-secondary">
                        <?= number_format(count(array_filter($rows, fn($r) => (int)($r['is_active'] ?? 1) !== 1))) ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="admin-card">
    <div class="admin-card-header">
        <div>
            <h5 class="mb-0">Lecturer List</h5>
            <div class="text-muted small"><?= number_format(count($rows)) ?> record(s) found</div>
        </div>
    </div>

    <div class="admin-card-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead>
                    <tr>
                        <th style="width:80px;">ID</th>
                        <th>Lecturer</th>
                        <th>Username</th>
                        <th>Email</th>
                        <th style="width:130px;">Status</th>
                        <th style="width:160px;">Created</th>
                        <th style="width:260px;" class="text-end">Action</th>
                    </tr>
                </thead>

                <tbody>
                    <?php if (!$rows): ?>
                        <tr>
                            <td colspan="7" class="text-center text-muted py-4">No lecturers found.</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($rows as $row): ?>
                            <?php
                                $id = (int)($row['id'] ?? 0);
                                $name = trim((string)($row['full_name'] ?? ''));
                                $username = trim((string)($row['username'] ?? ''));
                                $email = trim((string)($row['email'] ?? ''));
                                $active = (int)($row['is_active'] ?? 1);

                                $status = $active === 1 ? 'Active' : 'Inactive';
                                $badgeClass = $active === 1 ? 'bg-success' : 'bg-secondary';

                                $created = trim((string)($row['created_at'] ?? ''));
                                if ($created === '' || $created === '0000-00-00' || $created === '0000-00-00 00:00:00') {
                                    $createdText = '—';
                                } else {
                                    $time = strtotime($created);
                                    $createdText = $time ? date('d M Y', $time) : $created;
                                }
                            ?>

                            <tr>
                                <td class="fw-semibold"><?= $id ?></td>

                                <td>
                                    <div class="fw-semibold">
                                        <?= esc($name !== '' ? $name : ('Lecturer #' . $id)) ?>
                                    </div>
                                    <div class="small text-muted">Lecturer ID: <?= $id ?></div>
                                </td>

                                <td><?= esc($username !== '' ? $username : '—') ?></td>

                                <td>
                                    <?php if ($email !== ''): ?>
                                        <a href="mailto:<?= esc($email) ?>" class="text-decoration-none">
                                            <?= esc($email) ?>
                                        </a>
                                    <?php else: ?>
                                        <span class="text-muted">—</span>
                                    <?php endif; ?>
                                </td>

                                <td>
                                    <span class="badge <?= esc($badgeClass) ?>">
                                        <?= esc($status) ?>
                                    </span>
                                </td>

                                <td><?= esc($createdText) ?></td>

                                <td class="text-end">
                                    <button
                                        type="button"
                                        class="btn btn-outline-primary btn-sm"
                                        data-bs-toggle="modal"
                                        data-bs-target="#editLecturerModal<?= $id ?>"
                                    >
                                        Edit
                                    </button>

                                    <form method="post" class="d-inline">
                                        <input type="hidden" name="action" value="toggle_status">
                                        <input type="hidden" name="id" value="<?= $id ?>">
                                        <button class="btn btn-outline-secondary btn-sm">
                                            <?= $active === 1 ? 'Deactivate' : 'Activate' ?>
                                        </button>
                                    </form>

                                    <form method="post" class="d-inline" onsubmit="return confirm('Delete this lecturer?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= $id ?>">
                                        <button class="btn btn-outline-danger btn-sm">Delete</button>
                                    </form>
                                </td>
                            </tr>

                            <?php
$editModals[] = '
<div class="modal fade" id="editLecturerModal'.$id.'" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <form method="post" class="modal-content border-0 shadow">
            <input type="hidden" name="action" value="update">
            <input type="hidden" name="id" value="'.$id.'">

            <div class="modal-header">
                <h5 class="modal-title">Edit Lecturer</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Lecturer Name *</label>
                    <input type="text" name="full_name" class="form-control" value="'.esc($name).'" required>
                </div>

                <div class="mb-3">
                    <label class="form-label">Username *</label>
                    <input type="text" name="username" class="form-control" value="'.esc($username).'" required>
                </div>

                <div class="mb-3">
                    <label class="form-label">Email</label>
                    <input type="email" name="email" class="form-control" value="'.esc($email).'">
                </div>

                <div class="mb-1">
                    <label class="form-label">New Password</label>
                    <input type="password" name="password" class="form-control">
                    <div class="form-text">Leave blank to keep current password.</div>
                </div>
            </div>

            <div class="modal-footer">
                <button class="btn btn-admin-primary">
                    Save Changes
                </button>
            </div>
        </form>
    </div>
</div>';
?>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?= implode('', $editModals) ?>
<div class="modal fade" id="addLecturerModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <form method="post" class="modal-content border-0 shadow">
            <input type="hidden" name="action" value="create">

            <div class="modal-header">
                <h5 class="modal-title">Add Lecturer</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Lecturer Name *</label>
                    <input type="text" name="full_name" class="form-control" required>
                </div>

                <div class="mb-3">
                    <label class="form-label">Username *</label>
                    <input type="text" name="username" class="form-control" required>
                    <div class="form-text">Example: lect2</div>
                </div>

                <div class="mb-3">
                    <label class="form-label">Email</label>
                    <input type="email" name="email" class="form-control">
                </div>

                <div class="mb-1">
                    <label class="form-label">Password *</label>
                    <input type="password" name="password" class="form-control" required>
                    <div class="form-text">Use a secure password for lecturer login.</div>
                </div>
            </div>

            <div class="modal-footer">
                <button class="btn btn-admin-primary">
                    <i class="bi bi-check-circle me-1"></i>
                    Save Lecturer
                </button>
            </div>
        </form>
    </div>
</div>

<?php require_once __DIR__ . '/../../includes/admin_layout_bottom.php'; ?>