<?php
header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

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

require_once '../config.php';
require_once '../demo_helpers.php';

$response = array();

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

    // On the demo server the showcase account is code-only: it can never be
    // reached with a password. Approved schools enter via demo-access.php.
    if (DEMO_MODE && strtolower(trim($username)) === strtolower(DEMO_USERNAME)) {
        $response['success'] = false;
        $response['message'] = 'This demo requires an access code. Please request a demo.';
        echo json_encode($response);
        exit;
    }

    if (empty($username) || empty($password)) {
        $response['success'] = false;
        $response['message'] = 'Username and password are required';
        echo json_encode($response);
        exit;
    }

    try {
        $conn = getDBConnection();
        
        if (!$conn) {
            $response['success'] = false;
            $response['message'] = 'Database connection failed';
            echo json_encode($response);
            exit;
        }
        
        // ── Brute-force throttle: block an IP after too many recent failures ──
        $clientIp = substr((string) ($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'), 0, 45);
        $conn->query(
            "CREATE TABLE IF NOT EXISTS login_attempts (
                id INT AUTO_INCREMENT PRIMARY KEY,
                ip VARCHAR(45) NOT NULL,
                username VARCHAR(190) NULL,
                success TINYINT(1) NOT NULL DEFAULT 0,
                attempted_at DATETIME NOT NULL,
                INDEX idx_ip_time (ip, attempted_at)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"
        );

        // Fail open if the table is unavailable (e.g. DB user lacks CREATE) so
        // login never breaks; the throttle simply does not engage.
        $recentFails = 0;
        if ($rl = $conn->prepare(
            "SELECT COUNT(*) AS c FROM login_attempts
             WHERE ip = ? AND success = 0 AND attempted_at > (NOW() - INTERVAL 15 MINUTE)"
        )) {
            $rl->bind_param('s', $clientIp);
            $rl->execute();
            $recentFails = (int) ($rl->get_result()->fetch_assoc()['c'] ?? 0);
            $rl->close();
        }

        if ($recentFails >= 8) {
            $response['success'] = false;
            $response['message'] = 'Too many failed attempts. Please try again in about 15 minutes.';
            echo json_encode($response);
            exit;
        }

        $recordAttempt = function (int $ok) use ($conn, $clientIp, $username): void {
            $u = substr((string) $username, 0, 190);
            if ($st = $conn->prepare("INSERT INTO login_attempts (ip, username, success, attempted_at) VALUES (?, ?, ?, NOW())")) {
                $st->bind_param('ssi', $clientIp, $u, $ok);
                $st->execute();
                $st->close();
            }
        };

        $stmt = $conn->prepare("SELECT id, username, password, full_name, role FROM users WHERE username = ?");
        
        if (!$stmt) {
            $response['success'] = false;
            $response['message'] = 'Query prepare failed: ' . $conn->error;
            echo json_encode($response);
            exit;
        }
        
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 1) {
            $user = $result->fetch_assoc();

            $pwd_ok = !empty($user['password']) && password_verify($password, $user['password']);
            // Legacy: user_management.php stored passwords as md5() — upgrade on login
            if (!$pwd_ok && !empty($user['password']) && $user['password'] === md5($password)) {
                $pwd_ok   = true;
                $new_hash = password_hash($password, PASSWORD_BCRYPT);
                $up = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
                $up->bind_param('si', $new_hash, $user['id']);
                $up->execute();
                $up->close();
            }

            if ($pwd_ok) {
                session_regenerate_id(true);
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['full_name'] = $user['full_name'] ?: $user['username'];
                $_SESSION['role'] = $user['role'] ?: 'admin';

                // Update last login
                $conn->query("UPDATE users SET last_login = NOW() WHERE id = " . $user['id']);

                // If teacher/tutor: store assigned classes and subjects in session
                if ($user['role'] === 'tutor') {
                    $tStmt = $conn->prepare(
                        "SELECT classes_assigned, subjects_taught FROM staff WHERE user_id = ? LIMIT 1"
                    );
                    $tStmt->bind_param('i', $user['id']);
                    $tStmt->execute();
                    $staffRow = $tStmt->get_result()->fetch_assoc();
                    $tStmt->close();

                    $_SESSION['teacher_classes'] = $staffRow
                        ? array_values(array_filter(array_map('trim', explode(',', $staffRow['classes_assigned'] ?? ''))))
                        : [];
                    $_SESSION['teacher_subjects'] = $staffRow
                        ? array_values(array_filter(array_map('trim', explode(',', $staffRow['subjects_taught'] ?? ''))))
                        : [];
                }

                // Log activity
                logActivity($conn, $user['id'], 'Login', 'User logged in');

                $recordAttempt(1);
                $response['success'] = true;
                $response['message'] = 'Login successful';
            } else {
                $response['success'] = false;
                $response['message'] = 'Invalid username or password';
                $recordAttempt(0);
            }

        } else {
            $response['success'] = false;
            $response['message'] = 'Invalid username or password';
                $recordAttempt(0);
        }

        $stmt->close();
        $conn->close();
    } catch (Exception $e) {
        $response['success'] = false;
        $response['message'] = 'Error: ' . $e->getMessage();
    }
} else {
    $response['success'] = false;
    $response['message'] = 'Invalid request method';
}

echo json_encode($response);
?>