<?php
require_once __DIR__ . "/config.php";
session_start();

header('Content-Type: application/json');

/* ==============================
   LOGIN ATTEMPT CONTROL
============================== */

if (!isset($_SESSION['login_attempts'])) {
    $_SESSION['login_attempts'] = 0;
}

if ($_SESSION['login_attempts'] >= 3) {
    echo json_encode([
        'success' => false,
        'message' => 'Account locked. Contact administrator.'
    ]);
    exit();
}

/* ==============================
   GET INPUT
============================== */

$username = trim($_POST['username'] ?? '');

if ($username === '') {
    echo json_encode([
        'success' => false,
        'message' => 'Please enter your username'
    ]);
    exit();
}

/* ==============================
   PREPARE QUERY
============================== */

$stmt = $conn->prepare("
    SELECT id, name, photo, phone, house, status
    FROM teachers
    WHERE username = ?
    LIMIT 1
");

if (!$stmt) {
    echo json_encode([
        'success' => false,
        'message' => 'System error. Try again.'
    ]);
    exit();
}

$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();

/* ==============================
   CHECK USER EXISTS
============================== */

if ($result->num_rows !== 1) {
    $_SESSION['login_attempts']++;
    echo json_encode([
        'success' => false,
        'message' => 'Username not found'
    ]);
    exit();
}

$teacher = $result->fetch_assoc();

/* ==============================
   CHECK ACCOUNT STATUS
============================== */

if ((int)$teacher['status'] !== 1) {
    echo json_encode([
        'success' => false,
        'message' => 'Account disabled'
    ]);
    exit();
}

/* ==============================
   STORE VERIFIED USERNAME IN SESSION
============================== */

$_SESSION['verified_username'] = $username;
$_SESSION['verified_teacher_id'] = $teacher['id'];

/* ==============================
   BUILD PHOTO URL
============================== */

$photoFile = $teacher['photo'] ?? '';
if ($photoFile !== '' && file_exists(__DIR__ . '/admin/uploads/teachers/' . $photoFile)) {
    $photoUrl = 'admin/uploads/teachers/' . $photoFile;
} else {
    $photoUrl = 'admin/uploads/teachers/default.png';
}

/* ==============================
   RESPONSE
============================== */

echo json_encode([
    'success' => true,
    'name'    => $teacher['name'],
    'photo'   => $photoUrl,
    'phone'   => $teacher['phone'],
    'house'   => $teacher['house'],
]);
exit();
