<?php
require '../db.php';
require '../functions.php';

header('Content-Type: application/json');
$villager = requireVillagerToken($pdo);

try {
    $stmt = $pdo->prepare("SELECT v.fullname, v.photo, v.address, v.age, v.passstartdate, v.passenddate,
        v.passactive, v.barcodetext, p.name AS panchayatname
        FROM villager v LEFT JOIN panchayat p ON p.id = v.panchayatid
        WHERE v.id = ? AND v.isdeleted = 0");
    $stmt->execute([$villager['id']]);
    $v = $stmt->fetch();

    if (!$v || $v['passactive'] != 1) {
        jsonOut(false, 'You do not have an active pass yet');
    }

    $vehiclestmt = $pdo->prepare("SELECT vehiclenumber FROM villagervehicle WHERE villagerid = ? AND isdeleted = 0");
    $vehiclestmt->execute([$villager['id']]);
    $vehicles = array_column($vehiclestmt->fetchAll(), 'vehiclenumber');

    jsonOut(true, '', [
        'fullname' => $v['fullname'],
        'photo' => $v['photo'],
        'address' => $v['address'] . ', ' . $v['panchayatname'] . ', Divar',
        'age' => $v['age'],
        'validfrom' => $v['passstartdate'],
        'validuntil' => $v['passenddate'],
        'barcodetext' => $v['barcodetext'],
        'vehicles' => $vehicles,
    ]);
} catch (Exception $e) {
    logDebug('[api_getpass] ' . $e->getMessage());
    jsonOut(false, 'Something went wrong. Please try again.');
}
