<?php

namespace App\Http\Controllers;


use Carbon\Carbon;
use App\Models\Ticket;
use App\Models\Booking;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Thenextweb\PassGenerator;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Response;


class PassController extends Controller
{
    

    public function generatePass(Request $request, $booking_id)
    {
        try {
            // Fetch booking with relationships to reduce queries
            $booking = Booking::where('id', $booking_id)
                        ->firstOrFail();

            $ticket = Ticket::where('id', $booking->ticket_id)->first();
            $event = Ticket::where('id', $booking->event_id)->first();

            // Set runtime configuration for PassGenerator
            $passConfig = [
                'certificate_store_path' => env('CERTIFICATE_PATH', public_path('certificates/apple_wallet.p12')),
                'certificate_store_password' => env('CERTIFICATE_PASS', 'CB_12345'),
                'wwdr_certificate_path' => env('WWDR_CERTIFICATE', public_path('certificates/AppleWWDR.pem')),
                'pass_type_identifier' => env('PASS_TYPE_IDENTIFIER', 'pass.com.eventmieprofullyloaded.eventmie'),
                'organization_name' => env('ORGANIZATION_NAME', 'Eventmie'),
                'team_identifier' => env('TEAM_IDENTIFIER', 'pass.com.eventmieprofullyloaded.eventmie'),
            ];

            
            // Validate configuration
            if (empty($passConfig['certificate_store_path']) || !file_exists($passConfig['certificate_store_path'])) {
                Log::error('Certificate file missing or not configured', ['path' => $passConfig['certificate_store_path']]);
                return response()->json(['error' => 'Certificate file not found'], 500);
            }
            if (!is_readable($passConfig['certificate_store_path'])) {
                Log::error('Certificate file not readable', ['path' => $passConfig['certificate_store_path']]);
                return response()->json(['error' => 'Certificate file not readable'], 500);
            }
            if (empty($passConfig['wwdr_certificate_path']) || !file_exists($passConfig['wwdr_certificate_path'])) {
                Log::error('WWDR certificate file missing or not configured', ['path' => $passConfig['wwdr_certificate_path']]);
                return response()->json(['error' => 'WWDR certificate file not found'], 500);
            }
            if (!is_readable($passConfig['wwdr_certificate_path'])) {
                Log::error('WWDR certificate file not readable', ['path' => $passConfig['wwdr_certificate_path']]);
                return response()->json(['error' => 'WWDR certificate file not readable'], 500);
            }
            if (empty($passConfig['pass_type_identifier']) || empty($passConfig['team_identifier'])) {
                Log::error('Pass type identifier or team identifier not configured');
                return response()->json(['error' => 'Pass configuration incomplete'], 500);
            }

            // Set configuration for PassGenerator
            config(['passgenerator' => $passConfig]);

            
            // Define pass identifier for retrieval
            $pass_identifier = 'eventmie-pass-' . $booking->id;

            
            // Initialize PassGenerator with pass identifier
            $pass = new PassGenerator($pass_identifier);

            // Define pass data
            $pass_definition = [
                'description' => $event->title ?? 'Event Ticket',
                'formatVersion' => 1,
                'organizationName' => $passConfig['organization_name'],
                'passTypeIdentifier' => $passConfig['pass_type_identifier'],
                'serialNumber' => (string) $booking->id,
                'teamIdentifier' => $passConfig['team_identifier'],
                'foregroundColor' => 'rgb(0, 0, 0)',
                'backgroundColor' => 'rgb(255, 255, 255)',
                'labelColor' => 'rgb(0, 0, 0)',
                'barcode' => [
                    'message' => $booking->order_number,
                    'format' => 'PKBarcodeFormatQR',
                    'messageEncoding' => 'iso-8859-1',
                    'altText' => $booking->order_number,
                ],
                'eventTicket' => [
                    'headerFields' => [
                        [
                            'key' => 'event',
                            'label' => 'Event',
                            'value' => Str::limit($event->title ?? 'Untitled Event', 64),
                        ],
                    ],
                    'primaryFields' => [
                        [
                            'key' => 'ticket',
                            'label' => 'Ticket Number',
                            'value' => $booking->order_number,
                        ],
                    ],
                    'secondaryFields' => [
                        [
                            'key' => 'date',
                            'label' => 'Date',
                            'value' => Carbon::parse($event->start_date)->format('Y-m-d H:i'),
                            'dateStyle' => 'PKDateStyleMedium',
                            'timeStyle' => 'PKDateStyleShort',
                        ],
                        [
                            'key' => 'location',
                            'label' => 'Location',
                            'value' => Str::limit($event->address ?? 'TBD', 64),
                        ],
                    ],
                    'auxiliaryFields' => [
                        [
                            'key' => 'ticketType',
                            'label' => 'Ticket Type',
                            'value' => $ticket->title ?? 'General Admission',
                        ],
                    ],
                    'backFields' => [
                        [
                            'key' => 'ticketNumber',
                            'label' => 'Ticket Number',
                            'value' => $booking->order_number,
                        ],
                        [
                            'key' => 'eventName',
                            'label' => 'Event Name',
                            'value' => $event->title ?? 'Untitled Event',
                        ],
                        [
                            'key' => 'instructions',
                            'label' => 'Instructions',
                            'value' => 'Please present this pass at the event entrance.',
                        ],
                    ],
                ],
                'relevantDate' => Carbon::parse($event->start_date)->toIso8601String(),
               "locations" => [
                    [
                        "latitude" => $event->latitude ?? 0,
                        "longitude" => $event->longitude ?? 0,  
                        "relevantText" => "Event Location",
                        "relevantDate" => Carbon::parse($event->start_date)->toIso8601String(),
                       
                        
                    ]
                ],
                

            ];

            
            // Set pass definition
            $pass->setPassDefinition($pass_definition);

            
            // Add assets to the PKPass package
            $pass->addAsset(public_path('/img/background.png'));
            // $pass->addAsset(asset('resources/assets/wallet/thumbnail.png'));
            $pass->addAsset(public_path('/img/icon.png'));
            $pass->addAsset(public_path('/img/logo.png'));

        
            

            // Generate .pkpass file
            try {
                
                $pkpassContent = $pass->create();
            } catch (\Throwable $e) {

                
                Log::error('Pass creation failed', [
                    'booking_id' => $booking_id,
                    'error' => $e->getMessage(),
                ]);
                return response()->json(['error' => 'Failed to generate pass', 'message' => $e->getMessage()]);
            }
            
            if (!$pkpassContent) {
                Log::error('Empty PKPass content', ['booking_id' => $booking_id]);
                return response()->json(['error' => 'Failed to generate pass']);
            }

            // return new Response($pkpassContent, 200, [
            //     'Content-Transfer-Encoding' => 'binary',
            //     'Content-Description' => 'File Transfer',
            //     'Content-Disposition' => 'attachment; filename="pass.pkpassContent"',
            //     'Content-length' => strlen($pkpassContent),
            //     'Content-Type' => PassGenerator::getPassMimeType(),
            //     'Pragma' => 'no-cache',
            // ]);

            // Stream the .pkpass file with appropriate headers
            // return Response::streamDownload(function () use ($pkpassContent) {
            //     echo $pkpassContent;
            // }, "event-ticket-{$booking->order_number}.pkpass", [
            //     'Content-Type' => 'application/vnd.apple.pkpass',
            //     'Content-Length' => strlen($pkpassContent),
            //     'Cache-Control' => 'no-cache',
            // ]);


            // Return JSON response with base64-encoded .pkpass content
            // $filename = "event-ticket-{$booking->order_number}.pkpass";
            // $base64Content = base64_encode($pkpassContent);
            // return response()->json([
            //     'status' => 'success',
            //     'data' => [
            //         'pass' => $base64Content,
            //         'filename' => $filename,
            //         'content_type' => 'application/vnd.apple.pkpass',
            //     ],
            // ]);

                // Save .pkpass to temporary file
            $filename = "event-ticket-{$booking->order_number}.pkpass";
            $tempPath = public_path("storage/passes/{$filename}");
            Storage::disk('public')->put("passes/{$filename}", $pkpassContent);
            Log::info('Saved .pkpass to temporary file', ['path' => $tempPath, 'booking_id' => $booking_id]);

            // Verify file was created
            if (!file_exists($tempPath)) {
                Log::error('Failed to save .pkpass file', ['path' => $tempPath, 'booking_id' => $booking_id]);
                return response()->json(['error' => 'Failed to save pass file'], 500);
            }

       

            // // Serve the .pkpass file
            return response()->json(['status' => 'true'])->header('Content-Type', 'application/vnd.apple.pkpass')
                ->header('Content-Disposition', 'attachment; filename="' . $filename . '"')
                ->header('Content-Length', filesize($tempPath))
                ->header('Cache-Control', 'no-cache')
                ->header('Pragma', 'no-cache')
                ->setContent(file_get_contents($tempPath));
            

            //  // Clean up temporary file after response
            // register_shutdown_function(function () use ($tempPath) {
            //     if (file_exists($tempPath)) {
            //         unlink($tempPath);
            //         Log::info('Deleted temporary .pkpass file', ['path' => $tempPath]);
            //     }
            // });
            // dd($response);
            return $response;

        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json(['error' => 'Booking not found or unauthorized'], 404);
        } catch (\Exception $e) {
            Log::error('Pass generation failed', [
                'booking_id' => $booking_id,
                'error' => $e->getMessage(),
            ]);
            return response()->json(['error' => 'Internal server error', 'message' => $e->getMessage()], 500);
        }
    }
}
