<?php
require_once __DIR__ . '/vendor/autoload.php';

use Illuminate\Database\Capsule\Manager as Capsule;
use App\Models\Voter;
use App\Models\Booth;

// Bootstrap Laravel (minimal) by including the app
$app = require __DIR__ . '/bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();

function line($text='') { echo $text . "\n"; }

line('=== Import Integrity Verification ===');

$booth = Booth::first();
if (!$booth) {
    line('No booth found. Aborting.');
    exit(1);
}
line('Booth: #' . $booth->booth_number . ' Address: ' . $booth->booth_address);

$voters = Voter::where('booth_id', $booth->id)->orderBy('serial_number')->get();
$count = $voters->count();
line('Total voters fetched for booth: ' . $count);

// 1. Check serial continuity
$missingSerials = [];
$last = null;
foreach ($voters as $v) {
    if ($last !== null && $v->serial_number != $last + 1) {
        // Allow gaps only if OCR parsed numbers (rare); collect missing range
        for ($i = $last + 1; $i < $v->serial_number; $i++) { $missingSerials[] = $i; }
    }
    $last = $v->serial_number;
}
if (empty($missingSerials)) {
    line('Serial continuity: OK (no gaps)');
} else {
    line('Serial continuity gaps: ' . implode(',', $missingSerials));
}

// 2. Duplicate voter IDs
$dupIds = $voters->groupBy('voter_id_number')->filter(function($g){ return $g->count() > 1; });
if ($dupIds->isEmpty()) {
    line('Duplicate voter IDs: NONE');
} else {
    line('Duplicate voter IDs detected:');
    foreach ($dupIds as $id => $group) {
        line('  ' . $id . ' serials: ' . $group->pluck('serial_number')->join(','));
    }
}

// 3. Year of birth vs age check
$ybMismatches = [];
$currentYear = (int)date('Y');
foreach ($voters as $v) {
    if ($v->age && $v->year_of_birth && ($currentYear - (int)$v->age) != (int)$v->year_of_birth) {
        $ybMismatches[] = $v->serial_number;
    }
}
if (empty($ybMismatches)) {
    line('Year of birth consistency: OK');
} else {
    line('Year of birth mismatches at serials: ' . implode(',', $ybMismatches));
}

// 4. Sample output of first 10 voters
line('\nSample (first 10 voters):');
foreach ($voters->take(10) as $v) {
    line(sprintf('%3d | %s | %s | age:%s yob:%s',
        $v->serial_number,
        $v->voter_id_number,
        $v->name,
        $v->age ?? '-',
        $v->year_of_birth ?? '-'
    ));
}

// 5. Target serial (Sekar ~ 44) if present
$sekar = Voter::where('name', 'Sekar')->first();
if ($sekar) {
    line('\nSekar record: serial=' . $sekar->serial_number . ' voter_id=' . $sekar->voter_id_number . ' age=' . ($sekar->age ?? '-') . ' yob=' . ($sekar->year_of_birth ?? '-'));
} else {
    line('\nSekar record not found by exact name.');
}

line('\nVerification complete.');
