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

header('Content-Type: application/json');
$checker = requireCheckerToken($pdo);

$barcodetext = cleanInput($_POST['barcodetext'] ?? '');

if ($barcodetext === '') {
    jsonOut(false, 'Barcode value is required');
}

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

    if (!$v) {
        $log = $pdo->prepare("INSERT INTO ridelog (villagerid, checkerid, result) VALUES (NULL, ?, 'invalid')");
        $log->execute([$checker['id']]);
        jsonOut(false, 'Pass not recognized', ['result' => 'invalid']);
    }

    if ($v['passactive'] != 1) {
        $result = 'inactive';
    } elseif ($v['passenddate'] && strtotime($v['passenddate']) < strtotime(date('Y-m-d'))) {
        $result = 'expired';
    } else {
        $result = 'valid';
    }

    $log = $pdo->prepare("INSERT INTO ridelog (villagerid, checkerid, result) VALUES (?, ?, ?)");
    $log->execute([$v['id'], $checker['id'], $result]);

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

    jsonOut($result === 'valid', $result === 'valid' ? 'Pass verified successfully' : 'Pass is ' . $result, [
        'result' => $result,
        'fullname' => $v['fullname'],
        'photo' => $v['photo'],
        'address' => $v['address'] . ', ' . $v['panchayatname'] . ', Divar',
        'passenddate' => $v['passenddate'],
        'vehicles' => $vehicles,
    ]);
} catch (Exception $e) {
    logDebug('[api_scanpass] ' . $e->getMessage());
    jsonOut(false, 'Something went wrong. Please try again.');
}
