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

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

if (!isset($data['phone'])) {
    echo json_encode(['success' => false, 'error' => 'Missing phone number']);
    exit;
}

$phone = $data['phone'];

try {
    // Find students by parent phone
    $stmt = $pdo->prepare("SELECT s.*, b.bus_number, b.id as bus_id FROM students s LEFT JOIN buses b ON s.bus_id = b.id WHERE s.parent_phone = ?");
    $stmt->execute([$phone]);
    $students = $stmt->fetchAll();

    if (count($students) > 0) {
        // Generate session token for parent
        $token = bin2hex(random_bytes(32));
        
        // Store token in session or cache (simplified: we'll just return it)
        echo json_encode([
            'success' => true,
            'token' => $token,
            'students' => $students
        ]);
    } else {
        echo json_encode(['success' => false, 'error' => 'No students found for this phone number']);
    }
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'error' => 'Database error']);
}
?>
