<?php

use App\Http\Controllers\CharacteristicApprovalController;
use App\Http\Controllers\ProductionOrderController;
// use App\Http\Controllers\FileUploadController;
use App\Http\Controllers\VisitorBadgeController;
use App\Models\EquipmentMaster;
use App\Models\User;
use Filament\Facades\Filament;
use Illuminate\Http\Request;
// use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Route;
use thiagoalessio\TesseractOCR\TesseractOCR;
use Carbon\Carbon;

Route::get('/', function () {
    return redirect('/admin');
});

// Route::get('/admin', function () {
//     return redirect('/admin/welcome');
// });

// Route::get('/password-reset/approve/{token}', function ($token) {

//     // $workerId = cache()->pull("password-reset-approval-{$token}");

//     $workerId = cache()->get("password-reset-approval-{$token}");

//     if (! $workerId) {
//         return response()->view('errors.password-reset-expired', [], 410);
//     }

//     $worker = User::findOrFail($workerId);


//     $resetToken = Password::broker()->createToken($worker);


//     $resetUrl = URL::temporarySignedRoute(
//         'filament.admin.auth.password-reset.reset',
//         Carbon::now()->addMinutes(60),
//         [
//             'email' => $worker->email,
//             'token' => $resetToken,
//         ]
//     );


//     return redirect()->to($resetUrl);

// })->middleware('signed')->name('password-reset.approve');

//..

Route::get('/sticker/preview/{path}', function ($path) {
    $file = storage_path('app/' . $path);

    if (!file_exists($file)) {
        abort(404);
    }

    return response()->file($file, [
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'inline',
    ]);
})->name('sticker.preview');

// ..Characteristic Approval Routes..//

Route::get('/characteristic/hold', [CharacteristicApprovalController::class, 'holdForm'])
    ->name('characteristic.hold')
    ->middleware('signed');

Route::post('/characteristic/hold-save', [CharacteristicApprovalController::class, 'holdSave'])
    ->name('characteristic.hold.save');

Route::get('/approval/hold-success', function () {
    return view('approval.hold-success');
})->name('approval.hold.success');

Route::get('/characteristic/reject', [CharacteristicApprovalController::class, 'rejectForm'])
    ->name('characteristic.reject')
    ->middleware('signed');

Route::post('/characteristic/reject-save', [CharacteristicApprovalController::class, 'rejectSave'])
    ->name('characteristic.reject.save');

Route::get('/approval/reject-success', function () {
    return view('approval.reject-success');
})->name('approval.reject.success');

Route::get('/characteristic/approve', [CharacteristicApprovalController::class, 'approveForm'])
    ->name('characteristic.approve')
    ->middleware('signed');

Route::post('/characteristic/approve-save', [CharacteristicApprovalController::class, 'approveSave'])
    ->name('characteristic.approve.save');

Route::get('/approval/approve-success', function () {
    return view('approval.approve-success');
})->name('approval.approve.success');

Route::get('/production-orders/print/{production_order}',
    [ProductionOrderController::class, 'print']
)->name('production-orders.print');

Route::get('production-orders/{production_order}/{plant_code}/printpanel',
    [ProductionOrderController::class, 'printpanel']
)->name('production-orders.printpanel');

Route::get('production-orders/{production_order}/{plant_code}/printItemSerial',
    [ProductionOrderController::class, 'printItemSerial']
)->name('production-orders.printItemSerial');

Route::get('production-orders/{production_order}/{plant_code}/{from_serial_no}/{to_serial_no}/exportSerial',
    [ProductionOrderController::class, 'exportSerial']
)->name('production-orders.exportSerial');

Route::get('/visitor-badge/{id}', [VisitorBadgeController::class, 'show'])
    ->name('visitor.badge');
// Route::get('/characteristic/approve', [CharacteristicApprovalController::class, 'approve'])
//     ->name('characteristic.approve')
//     ->middleware('signed');

// Route::post('/file-upload', [FileUploadController::class, 'upload'])->name('file.upload');

// Route::get('/characteristic/hold', [CharacteristicApprovalController::class, 'hold'])
//     ->name('characteristic.hold')
//     ->middleware('signed');

// Route::get('/characteristic/reject', [CharacteristicApprovalController::class, 'reject'])
//     ->name('characteristic.reject')
//     ->middleware('signed');

// routes/web.php

Route::post('/save-serials-to-session', function (Request $request) {
    session(['serial_numbers' => $request->serial_numbers]);

    return response()->json([
        'status' => 'success',
        'serial_numbers' => session('serial_numbers'),
    ]);
});

Route::get('/part-validation-image/{filename}', function ($filename) {
    $path = storage_path("app/private/uploads/PartValidation/{$filename}");

    if (! file_exists($path)) {
        abort(404, 'Image not found');
    }

    return response()->file($path);
})->name('part.validation.image');

Route::get('/workflow-image/{filename}', function ($filename) {
    $path = storage_path("app/private/uploads/LaserDocs/{$filename}");

    if (! file_exists($path)) {
        abort(404, 'Image not found');
    }

    return response()->file($path);
})->name('workflow.image');

// web.php
Route::post('/temp-upload', function (Request $request) {
    if (! $request->hasFile('photo')) {
        return response()->json(['success' => false], 400);
    }

    $file = $request->file('photo');
    $filename = 'capture_'.time().'.jpeg';
    $path = $file->storeAs('temp', $filename, 'local'); // storage/app/temp

    return response()->json([
        'success' => true,
        'path' => $path,
    ]);
});

Route::post('/verify-ocr', function (Request $request) {

    if (! $request->has('path')) {
        return response()->json(['success' => false, 'error' => 'No file path provided']);
    }

    $filePath = storage_path('app/private/temp/'.basename($request->path));

    if (! file_exists($filePath)) {
        return response()->json(['success' => false, 'error' => 'File not found']);
    }

    try {
        // $text = (new TesseractOCR($filePath))->lang('eng')->run();
        $text = (new TesseractOCR($filePath))
            ->executable('/usr/bin/tesseract')
            ->lang('eng')
            ->psm(6) // treats the image as a block of text
            ->config('tessedit_char_whitelist', '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')
            ->run();

        $text = trim($text); // remove whitespace

        if (empty($text)) {
            // No text found
            return response()->json(['success' => true, 'text' => 'Text not found']);
        }

        // return response()->json(['success' => true, 'text' => $text]);
        $lines = preg_split('/\r\n|\r|\n/', $text);
        $serials = array_filter(array_map('trim', $lines), fn ($line) => preg_match('/^[A-Za-z0-9]+$/', $line));

        return response()->json([
            'success' => true,
            'text' => array_values($serials), // reindex array
        ]);
    }
    // catch (\Exception $e) {
    //     return response()->json(['success' => false, 'error' => $e->getMessage()]);
    // }
    catch (\Exception $e) {
        // Log the full exception class and message
        \Log::error('Tesseract OCR failed', [
            'exception_class' => get_class($e),
            'message' => $e->getMessage(),
            'file' => $e->getFile(),
            'line' => $e->getLine(),
            'trace' => $e->getTraceAsString(),
        ]);

        // Return detailed error for debugging
        return response()->json([
            'success' => false,
            'error' => $e->getMessage(),
            'exception_class' => get_class($e),
            'file' => $e->getFile(),
            'line' => $e->getLine(),
            'trace' => $e->getTraceAsString(),
        ]);
    }
});

Route::get('/download/{equipmentNumber}', function ($equipmentNumber) {
    $model = EquipmentMaster::where('equipment_number', $equipmentNumber)->firstOrFail();

    if (! $model->attachment || ! Storage::disk('local')->exists($model->attachment)) {
        abort(404, 'File not found.');
    }

    return Storage::disk('local')->download($model->attachment);
})->name('download.attachment');

// Route::get('/admin/forgot-password', function () {
//     return view('auth.forgot-password');
// })->name('filament.admin.forgot-password');

//     Route::post('/admin/forgot-password', function(Request $request){

//     $validator = Validator::make($request->all(), [
//         'email'=>'required|email',
//         'old_password'=>'required',
//         'password'=>'required',
//         'password_confirmation'=>'required'
//     ]);

//     if($validator->fails()){
//         return response()->json([
//             'emailError' => $validator->errors()->first('email'),
//             'oldPasswordError' => $validator->errors()->first('old_password'),
//             'newPasswordError' => $validator->errors()->first('password'),
//             'confirmPasswordError' => $validator->errors()->first('password_confirmation')
//         ]);
//     }

//     $user = User::where('email',$request->email)->first();
//     if(!$user){
//         return response()->json(['passwordError'=>'No user found with this email.']);
//     }

//     if(!Hash::check($request->old_password, $user->password)){
//         return response()->json(['oldPasswordError'=>'Old password does not match']);
//     }

//     if($request->password != $request->password_confirmation){
//         return response()->json(['newPasswordError'=>'New password and confirm password do not match']);
//     }

//     $user->password = Hash::make($request->password);
//     $user->save();

//     return response()->json(['success'=>'Password changed successfully!']);
// })->name('filament.admin.forgot-password.otp');

// Route::post('/admin/check-email', function(Request $request){
//     $request->validate(['email' => 'required|email']);
//     $exists = User::where('email', $request->email)->first();
//     return response()->json(['exists' => $exists]);
// })->name('admin.check-email');
