<?php
require_once '../config/database.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    die(json_encode(['error' => 'Method not allowed']));
}

$data = json_decode(file_get_contents('php://input'), true);

$student_code = $data['student_code'] ?? '';
$password = $data['password'] ?? '';

if (empty($student_code) || empty($password)) {
    http_response_code(400);
    die(json_encode(['error' => 'Student code and password are required']));
}

try {
    $stmt = $pdo->prepare("SELECT * FROM learners WHERE student_code = ? AND is_active = TRUE");
    $stmt->execute([$student_code]);
    $learner = $stmt->fetch();

    if (!$learner || !password_verify($password, $learner['password_hash'])) {
        http_response_code(401);
        die(json_encode(['error' => 'Invalid credentials']));
    }

    // Generate session token
    $session_token = bin2hex(random_bytes(32));
    
    // Store session in PHP session
    session_start();
    $_SESSION['learner_id'] = $learner['learner_id'];
    $_SESSION['student_code'] = $learner['student_code'];
    $_SESSION['full_name'] = $learner['full_name'];
    $_SESSION['account_type'] = $learner['account_type'];
    $_SESSION['auth_token'] = $session_token;

    echo json_encode([
        'success' => true,
        'learner' => [
            'student_code' => $learner['student_code'],
            'full_name' => $learner['full_name'],
            'account_type' => $learner['account_type']
        ],
        'auth_token' => $session_token
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Authentication failed', 'details' => $e->getMessage()]);
}
?>
