<?php
require 'vendor/autoload.php';
$app = require_once 'bootstrap/app.php';
$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();

use App\Models\Student;
use Illuminate\Support\Facades\Crypt;

echo "=== Re-encrypting Biometric Templates ===\n\n";

$students = Student::whereNotNull('biometric_template')->get();

if ($students->isEmpty()) {
    echo "✅ No plaintext templates to encrypt.\n";
    exit;
}

$encrypted = 0;
$skipped = 0;

foreach ($students as $student) {
    // Get raw value without triggering accessor
    $raw = $student->getRawOriginal('biometric_template');

    // Check if already encrypted
    if (strpos($raw, 'eyJ') === 0 || strpos($raw, 'base64:') === 0) {
        echo "⏭️  Student #{$student->id} ({$student->name}) - already encrypted\n";
        $skipped++;
        continue;
    }

    // Encrypt and save
    try {
        $encrypted_value = Crypt::encryptString($raw);
        $student->update(['biometric_template' => $encrypted_value]);
        echo "✅ Student #{$student->id} ({$student->name}) - encrypted\n";
        $encrypted++;
    } catch (\Exception $e) {
        echo "❌ Student #{$student->id} ({$student->name}) - failed: {$e->getMessage()}\n";
    }
}

echo "\n--- Summary ---\n";
echo "Encrypted: {$encrypted}\n";
echo "Skipped: {$skipped}\n";
echo "Total: " . ($encrypted + $skipped) . "\n";
