<?php

use App\Http\Controllers\PdfController;
use App\Http\Controllers\PrintController;
use App\Mail\test;
use App\Models\EquipmentMaster;
use App\Models\InvoiceValidation;
use App\Models\Plant;
use App\Models\User;
use App\Models\WebPushSubscription;
use Filament\Facades\Filament;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;
use thiagoalessio\TesseractOCR\TesseractOCR;
use App\Http\Livewire\CustomLogin;
use App\Services\StickerPdfService;

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

    Route::get('/sticker/pdf/{item}/{serial}/{plantId}/{po}', [PrintController::class, 'generate']);

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

    // Route::post('/push/subscribe', function (Request $request) {
    //     $request->user()->updatePushSubscription(
    //         $request->endpoint,
    //         $request->keys['p256dh'],
    //         $request->keys['auth']
    //     );

    //     return response()->json(['success' => true]);
    // })->middleware('auth');

    // Route::post('/push/subscribe', function (Request $request) {
    // $user = Filament::auth()->user();

    //     abort_if(!$user, 401);

    //     $user->updatePushSubscription(
    //         $request->endpoint,
    //         $request->keys['p256dh'],
    //         $request->keys['auth'],
    //         $request->contentEncoding ?? 'aesgcm'
    //     );

    //     return response()->json(['success' => true]);
    // });

  Route::post('/push/subscribe', function (Request $request) {

    $user = Filament::auth()->user();
    abort_if(!$user, 401);

    $request->validate([
        'endpoint' => 'required|string',
        'keys.p256dh' => 'required|string',
        'keys.auth' => 'required|string',
    ]);

    WebPushSubscription::updateOrCreate(
        ['endpoint' => $request->endpoint],
        [
            'subscribable_type' => get_class($user),
            'subscribable_id'   => $user->id,
            'public_key'        => $request->keys['p256dh'],
            'auth_token'        => $request->keys['auth'],
            'content_encoding'  => $request->contentEncoding ?? 'aesgcm',
        ]
    );

    // WebPushSubscription::updateOrCreate(
    //     [
    //         'endpoint'          => $request->endpoint,
    //         'subscribable_type' => get_class($user),
    //         'subscribable_id'   => $user->id,
    //     ],
    //     [
    //         'public_key'       => $request->keys['p256dh'],
    //         'auth_token'       => $request->keys['auth'],
    //         'content_encoding' => $request->contentEncoding ?? 'aesgcm',
    //     ]
    // );


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


    // 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(
        '/stickers/{stickerId}/pdf/{plantId?}/{itemCharacteristicId?}',
        [PdfController::class, 'generate']
    )->name('stickers.pdf');

    Route::get(
        '/stickers/{stickerId}/pdf/{plantId?}/{itemCharacteristicId?}',
        [PdfController::class, 'generatePdf']
    )->name('stickers1.pdf');

    // Route::get('/stickers/pdf', [PdfController::class, 'generatePdf'])->name('stickers1.pdf');


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

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

        return response()->file($path);
    })->name('part.validation.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');
