<?php
// coordinator/login.php

declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

ini_set('display_errors', '1'); // test time only
ini_set('log_errors', '1');
error_reporting(E_ALL);

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

$db = null;

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

if (!$db || $db->connect_errno) {
    http_response_code(500);
    exit('Database connection failed.');
}

$db->set_charset('utf8mb4');

if (!function_exists('h')) {
    function h($value): string {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

function 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;
}

function column_exists(mysqli $db, string $table, string $column): bool {
    $safeTable = preg_replace('/[^a-zA-Z0-9_]/', '', $table);
    $safeCol   = $db->real_escape_string($column);
    $res = $db->query("SHOW COLUMNS FROM `{$safeTable}` LIKE '{$safeCol}'");
    return $res && $res->num_rows > 0;
}

function pass_ok(string $plain, string $stored): bool {
    $stored = trim($stored);

    if ($stored === '') {
        return false;
    }

    $info = password_get_info($stored);

    if (($info['algoName'] ?? 'unknown') !== 'unknown') {
        return password_verify($plain, $stored);
    }

    return hash_equals($stored, $plain);
}

/**
 * Already logged in
 */
$currentRole = strtolower((string)(
    $_SESSION['user_role']
    ?? $_SESSION['admin_role']
    ?? $_SESSION['role']
    ?? ($_SESSION['user']['role'] ?? '')
));

if (in_array($currentRole, ['coordinator', 'course_coordinator'], true)) {
    header('Location: /elms/coordinator/dashboard.php');
    exit;
}

$error = '';

if (!table_exists($db, 'elms_users')) {
    $error = 'elms_users table not found.';
}

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST' && $error === '') {
    $login = trim((string)($_POST['username'] ?? ''));
    $pass  = (string)($_POST['password'] ?? '');

    if ($login === '' || $pass === '') {
        $error = 'Please enter username/email and password.';
    } else {
        $selectCols = ['id'];
        $possibleCols = [
            'username',
            'email',
            'full_name',
            'name',
            'role_slug',
            'role',
            'role_code',
            'branch_id',
            'branch_ids',
            'password_hash',
            'plain_password',
            'password',
            'is_active',
            'status'
        ];

        foreach ($possibleCols as $col) {
            if (column_exists($db, 'elms_users', $col)) {
                $selectCols[] = $col;
            }
        }

        $whereParts = [];
        $bindValues = [];
        $bindTypes  = '';

        if (column_exists($db, 'elms_users', 'username')) {
            $whereParts[] = 'username = ?';
            $bindValues[] = $login;
            $bindTypes .= 's';
        }

        if (column_exists($db, 'elms_users', 'email')) {
            $whereParts[] = 'email = ?';
            $bindValues[] = $login;
            $bindTypes .= 's';
        }

        if (!$whereParts) {
            $error = 'No username/email column found in elms_users.';
        } else {
            $activeSql = '';

            if (column_exists($db, 'elms_users', 'is_active')) {
                $activeSql = ' AND is_active = 1 ';
            } elseif (column_exists($db, 'elms_users', 'status')) {
                $activeSql = " AND LOWER(status) IN ('active','1','enabled') ";
            }

            $sql = "
                SELECT " . implode(', ', array_map(fn($c) => "`$c`", $selectCols)) . "
                FROM elms_users
                WHERE (" . implode(' OR ', $whereParts) . ")
                {$activeSql}
                LIMIT 1
            ";

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

            if (!$stmt) {
                $error = 'SQL prepare failed: ' . $db->error;
            } else {
                $stmt->bind_param($bindTypes, ...$bindValues);
                $stmt->execute();
                $row = $stmt->get_result()->fetch_assoc();
                $stmt->close();

                if (!$row) {
                    $error = 'User not found or inactive.';
                } else {
                    $storedPassword = '';

                    if (!empty($row['password_hash'])) {
                        $storedPassword = (string)$row['password_hash'];
                    } elseif (!empty($row['plain_password'])) {
                        $storedPassword = (string)$row['plain_password'];
                    } elseif (!empty($row['password'])) {
                        $storedPassword = (string)$row['password'];
                    }

                    if (!pass_ok($pass, $storedPassword)) {
                        $error = 'Invalid password.';
                    } else {
                        $role = strtolower((string)(
                            $row['role_slug']
                            ?? $row['role']
                            ?? $row['role_code']
                            ?? ''
                        ));

                        if ($role === 'course_coordinator') {
                            $role = 'coordinator';
                        }

                        if ($role !== 'coordinator') {
                            $error = 'This login is only for coordinators.';
                        } else {
                            $name = $row['full_name']
                                ?? $row['name']
                                ?? $row['username']
                                ?? 'Coordinator';

                            $branchIds = [];

                            if (!empty($row['branch_ids'])) {
                                $decoded = json_decode((string)$row['branch_ids'], true);

                                if (is_array($decoded)) {
                                    $branchIds = array_values(array_filter(array_map('intval', $decoded)));
                                } else {
                                    $branchIds = array_values(array_filter(array_map('intval', explode(',', (string)$row['branch_ids']))));
                                }
                            }

                            if (!$branchIds && !empty($row['branch_id'])) {
                                $branchIds[] = (int)$row['branch_id'];
                            }

                            session_regenerate_id(true);

                            $_SESSION['user_id']     = (int)$row['id'];
                            $_SESSION['user_name']   = (string)$name;
                            $_SESSION['user_role']   = 'coordinator';
                            $_SESSION['branch_ids']  = $branchIds;

                            // Backward compatibility for old pages
                            $_SESSION['admin_id']    = (int)$row['id'];
                            $_SESSION['admin_name']  = (string)$name;
                            $_SESSION['admin_role']  = 'coordinator';
                            $_SESSION['role']        = 'coordinator';

                            $_SESSION['user'] = [
                                'id'         => (int)$row['id'],
                                'name'       => (string)$name,
                                'username'   => (string)($row['username'] ?? ''),
                                'email'      => (string)($row['email'] ?? ''),
                                'role'       => 'coordinator',
                                'branch_id'  => $row['branch_id'] ?? null,
                                'branch_ids' => implode(',', $branchIds),
                            ];

                            header('Location: /elms/coordinator/dashboard.php');
                            exit;
                        }
                    }
                }
            }
        }
    }
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Coordinator Login | EDEN ELMS</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

    <style>
        *{box-sizing:border-box}
        body{
            min-height:100vh;
            margin:0;
            background:#f4f6f9;
            font-family:Arial,sans-serif;
            color:#111827;
        }
        .login-page{
            min-height:100vh;
            display:flex;
            align-items:center;
            justify-content:center;
            padding:28px;
        }
        .login-box{
            width:100%;
            max-width:860px;
            min-height:460px;
            background:#fff;
            border:1px solid #e5e7eb;
            border-radius:30px;
            overflow:hidden;
            display:grid;
            grid-template-columns:1fr 1fr;
            box-shadow:0 30px 90px rgba(15,23,42,.10);
        }
        .login-brand-side{
            background:#6E1A37;
            color:#fff;
            padding:48px 42px;
            display:flex;
            flex-direction:column;
            justify-content:center;
            align-items:center;
            text-align:center;
        }
        .login-brand-side img{
            width:150px;
            background:#fff;
            border-radius:18px;
            padding:12px;
            margin-bottom:32px;
        }
        .login-brand-side h1{
            font-size:42px;
            font-weight:900;
            letter-spacing:2px;
            margin:0 0 14px;
            color:#fff;
        }
        .login-brand-side p{
            font-size:16px;
            color:#f3f4f6;
            margin:0;
            line-height:1.7;
        }
        .login-form-side{
            padding:48px 42px;
            display:flex;
            flex-direction:column;
            justify-content:center;
        }
        .login-head span{
            display:inline-block;
            font-size:11px;
            font-weight:900;
            letter-spacing:1px;
            text-transform:uppercase;
            color:#6b7280;
            margin-bottom:10px;
        }
        .login-head h2{
            font-size:28px;
            font-weight:900;
            margin:0;
            color:#111827;
        }
        .login-head p{
            font-size:13px;
            color:#6b7280;
            margin:8px 0 26px;
        }
        .form-label{
            font-size:13px;
            font-weight:800;
            color:#111827;
            margin-bottom:8px;
        }
        .form-control{
            height:48px;
            border-radius:14px;
            border:1px solid #d9dee7;
            background:#fff;
            padding:10px 14px;
            font-size:14px;
            box-shadow:none!important;
        }
        .form-control:focus{
            border-color:#111827;
        }
        .login-btn{
            width:100%;
            height:48px;
            border:0;
            border-radius:14px;
            background:#6E1A37;
            color:#fff;
            font-size:14px;
            font-weight:900;
            margin-top:8px;
        }
        .login-btn:hover{background:#000}
        .alert{
            border-radius:14px;
            font-size:13px;
            margin-bottom:16px;
        }
        .login-footer{
            margin-top:24px;
            text-align:center;
            font-size:12px;
            color:#6b7280;
        }
        @media(max-width:768px){
            .login-box{
                grid-template-columns:1fr;
                max-width:430px;
            }
            .login-brand-side{
                padding:38px 28px;
            }
            .login-brand-side img{
                width:125px;
                margin-bottom:22px;
            }
            .login-brand-side h1{
                font-size:30px;
            }
            .login-form-side{
                padding:34px 28px;
            }
        }
    </style>
</head>
<body>

<div class="login-page">
    <div class="login-box">

        <div class="login-brand-side">
            <img src="/elms/includes/logo/edden_logo.jpg" alt="Eden Campus">
            <h1>EDEN ELMS</h1>
            <p>Coordinator Learning Management Portal</p>
        </div>

        <div class="login-form-side">
            <div class="login-head">
                <span>Coordinator Login</span>
                <h2>Welcome Back</h2>
                <p>Sign in to continue your session</p>
            </div>

            <?php if ($error): ?>
                <div class="alert alert-danger py-2">
                    <?= h($error) ?>
                </div>
            <?php endif; ?>

            <form method="post" autocomplete="off">
                <div class="mb-3">
                    <label class="form-label">Username or Email</label>
                    <input type="text" name="username" class="form-control" required autofocus>
                </div>

                <div class="mb-3">
                    <label class="form-label">Password</label>
                    <input type="password" name="password" class="form-control" required>
                </div>

                <button type="submit" class="login-btn">
                    Sign in
                </button>
            </form>

            <div class="login-footer">
                &copy; <?= date('Y') ?> Eden Campus ELMS
            </div>
        </div>

    </div>
</div>

</body>
</html>