<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Models\Ticket;
use App\Models\ComplimentaryTicket;
use App\Models\Event;
use App\Models\Transaction;
use Carbon\Carbon;
use GuzzleHttp\Client;

class TicketsController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:view-tickets')->except(['analytics', 'verifyShow', 'verifyProcess']);
        $this->middleware('permission:view-metrics')->only('analytics');
    }

    public function index(Request $request)
    {
        $search = $request->get('search');
        $status = $request->get('status');
        $event = $request->get('event');
        $school = $request->get('school');
        $stkStatus = $request->get('stk_status');
        $perPage = $request->get('per_page', 50);

        $query = Ticket::with('event')
            ->leftJoin(DB::raw('(SELECT ticket_reference_number, stk_status FROM txn_logs WHERE id IN (SELECT MAX(id) FROM txn_logs GROUP BY ticket_reference_number)) as latest_txn'), 'tickets.reference', '=', 'latest_txn.ticket_reference_number')
            ->select('tickets.*', 'latest_txn.stk_status');

        // Search functionality
        if ($search) {
            $query->where(function ($q) use ($search) {
                $q->where('tickets.first_name', 'like', "%{$search}%")
                    ->orWhere('tickets.last_name', 'like', "%{$search}%")
                    ->orWhere('tickets.phone', 'like', "%{$search}%")
                    ->orWhere('tickets.email', 'like', "%{$search}%")
                    ->orWhere('tickets.school', 'like', "%{$search}%")
                    ->orWhere('tickets.reference', 'like', "%{$search}%");
            });
        }

        // Status filter
        if ($status) {
            $query->where('tickets.payment_status', $status);
        }

        // Event filter
        if ($event) {
            $query->where('tickets.event_id', $event);
        }

        // School filter
        if ($school) {
            $query->where('tickets.school', $school);
        }

        // STK Status filter
        if ($stkStatus) {
            $query->where('latest_txn.stk_status', $stkStatus);
        }

        // Order by payment_date (purchase date) descending, then fallback to created_at
        $tickets = $query->orderByDesc('tickets.id')
            ->orderByDesc('tickets.created_at')
            ->paginate($perPage)
            ->withQueryString();

        // Get all events for filter dropdown
        $events = Event::orderBy('name')->get();

        // Get all schools for filter dropdown
        $schools = Ticket::distinct()
            ->whereNotNull('school')
            ->pluck('school')
            ->sort()
            ->values();

        // Get ticket stats
        $ticketStats = [
            'total_tickets' => Ticket::count(),
            'total_paid' => Ticket::where('payment_status', 'completed')->count(),
            'total_pending' => Ticket::where('payment_status', 'pending')->count(),
            'total_failed' => Ticket::where('payment_status', 'failed')->count(),
            'total_revenue' => Ticket::where('payment_status', 'completed')->sum('total_amount'),
            'today_sales' => Ticket::where('payment_status', 'completed')
                ->whereDate('payment_date', today())->count(),
            'today_revenue' => Ticket::where('payment_status', 'completed')
                ->whereDate('payment_date', today())->sum('total_amount'),
            'this_month_sales' => Ticket::where('payment_status', 'completed')
                ->whereMonth('payment_date', now()->month)
                ->whereYear('payment_date', now()->year)->count(),
            'this_month_revenue' => Ticket::where('payment_status', 'completed')
                ->whereMonth('payment_date', now()->month)
                ->whereYear('payment_date', now()->year)->sum('total_amount'),
        ];

        return view('tickets.index', compact('tickets', 'events', 'schools', 'ticketStats', 'search', 'status', 'event', 'school', 'stkStatus', 'perPage'));
    }

    public function indexV2(Request $request)
    {
        $search = $request->get('search');
        $status = $request->get('status');
        $event = $request->get('event');
        $school = $request->get('school');
        $stkStatus = $request->get('stk_status');
        $perPage = $request->get('per_page', 50);

        $query = Ticket::with('event')
            ->leftJoin(DB::raw('(SELECT ticket_reference_number, stk_status FROM txn_logs WHERE id IN (SELECT MAX(id) FROM txn_logs GROUP BY ticket_reference_number)) as latest_txn'), 'tickets.reference', '=', 'latest_txn.ticket_reference_number')
            ->select('tickets.*', 'latest_txn.stk_status');

        if ($search) {
            $query->where(function ($q) use ($search) {
                $q->where('tickets.first_name', 'like', "%{$search}%")
                    ->orWhere('tickets.last_name', 'like', "%{$search}%")
                    ->orWhere('tickets.phone', 'like', "%{$search}%")
                    ->orWhere('tickets.email', 'like', "%{$search}%")
                    ->orWhere('tickets.school', 'like', "%{$search}%")
                    ->orWhere('tickets.reference', 'like', "%{$search}%");
            });
        }

        if ($status) {
            $query->where('tickets.payment_status', $status);
        }

        if ($event) {
            $query->where('tickets.event_id', $event);
        }

        if ($school) {
            $query->where('tickets.school', $school);
        }

        if ($stkStatus) {
            $query->where('latest_txn.stk_status', $stkStatus);
        }

        $tickets = $query->orderByDesc('tickets.id')
            ->orderByDesc('tickets.created_at')
            ->paginate($perPage)
            ->withQueryString();

        $events = Event::orderBy('name')->get();
        $schools = Ticket::distinct()->whereNotNull('school')->pluck('school')->sort()->values();

        // Calculate today's metrics
        $todaySales = Ticket::where('payment_status', 'completed')->whereDate('payment_date', today())->count();
        $todayRevenue = Ticket::where('payment_status', 'completed')->whereDate('payment_date', today())->sum('total_amount');
        $totalRevenue = Ticket::where('payment_status', 'completed')->sum('total_amount');

        // Calculate yesterday's metrics for comparison
        $yesterday = Carbon::yesterday();
        $yesterdaySales = Ticket::where('payment_status', 'completed')->whereDate('payment_date', $yesterday)->count();
        $yesterdayRevenue = Ticket::where('payment_status', 'completed')->whereDate('payment_date', $yesterday)->sum('total_amount');

        // Week-over-week comparison for total revenue
        $lastWeekStart = Carbon::today()->subWeeks(2)->startOfDay();
        $lastWeekEnd = Carbon::today()->subWeek()->endOfDay();
        $lastWeekRevenue = Ticket::where('payment_status', 'completed')
            ->whereBetween('payment_date', [$lastWeekStart, $lastWeekEnd])
            ->sum('total_amount');

        $thisWeekStart = Carbon::today()->subWeek()->startOfDay();
        $thisWeekEnd = Carbon::today()->endOfDay();
        $thisWeekRevenue = Ticket::where('payment_status', 'completed')
            ->whereBetween('payment_date', [$thisWeekStart, $thisWeekEnd])
            ->sum('total_amount');

        // Helper function to calculate percentage change
        $calculateChange = function ($current, $previous) {
            if ($previous == 0) {
                return $current > 0 ? '+100' : '0';
            }
            $change = (($current - $previous) / $previous) * 100;
            $formatted = number_format(abs($change), 0);
            return $change > 0 ? "+{$formatted}" : ($change < 0 ? "-{$formatted}" : "0");
        };

        // Helper function to determine direction
        $getDirection = function ($current, $previous) {
            if ($previous == 0) {
                return $current > 0 ? 'positive' : 'neutral';
            }
            $change = $current - $previous;
            return $change > 0 ? 'positive' : ($change < 0 ? 'negative' : 'neutral');
        };

        $ticketStats = [
            'total_tickets' => Ticket::count(),
            'total_paid' => Ticket::where('payment_status', 'completed')->count(),
            'total_pending' => Ticket::where('payment_status', 'pending')->count(),
            'total_failed' => Ticket::where('payment_status', 'failed')->count(),
            'total_revenue' => $totalRevenue,
            'today_sales' => $todaySales,
            'today_revenue' => $todayRevenue,
            'this_month_sales' => Ticket::where('payment_status', 'completed')->whereMonth('payment_date', now()->month)->whereYear('payment_date', now()->year)->count(),
            'this_month_revenue' => Ticket::where('payment_status', 'completed')->whereMonth('payment_date', now()->month)->whereYear('payment_date', now()->year)->sum('total_amount'),

            // Yesterday's data
            'yesterday_sales' => $yesterdaySales,
            'yesterday_revenue' => $yesterdayRevenue,

            // Percentage changes
            'total_revenue_change' => $calculateChange($thisWeekRevenue, $lastWeekRevenue) . '%',
            'today_sales_change' => $calculateChange($todaySales, $yesterdaySales) . '%',
            'today_revenue_change' => $calculateChange($todayRevenue, $yesterdayRevenue) . '%',

            // Change directions
            'total_revenue_direction' => $getDirection($thisWeekRevenue, $lastWeekRevenue),
            'today_sales_direction' => $getDirection($todaySales, $yesterdaySales),
            'today_revenue_direction' => $getDirection($todayRevenue, $yesterdayRevenue),
        ];

        return view('dashboard-v2', compact('tickets', 'events', 'schools', 'ticketStats', 'search', 'status', 'event', 'school', 'stkStatus', 'perPage'));
    }

    public function transactionsApi(Request $request)
    {
        $query = Ticket::with('event')
            ->leftJoin(DB::raw('(SELECT ticket_reference_number, stk_status FROM txn_logs WHERE id IN (SELECT MAX(id) FROM txn_logs GROUP BY ticket_reference_number)) as latest_txn'), 'tickets.reference', '=', 'latest_txn.ticket_reference_number')
            ->select('tickets.*', 'latest_txn.stk_status')
            ->orderByDesc('tickets.id')
            ->limit(1000);

        $tickets = $query->get();

        $rows = $tickets->map(function ($t) {
            $status = $t->payment_status === 'completed' ? 'Paid' : ($t->payment_status === 'pending' ? 'Pending' : 'Failed');
            $paymentDate = $t->payment_date ? (is_string($t->payment_date) ? $t->payment_date : $t->payment_date->format('Y-m-d H:i')) : '—';
            $created = $t->created_at ? $t->created_at->format('Y-m-d H:i') : '';
            return [
                'id' => (int) $t->id,
                'reference' => (string) $t->reference,
                'customer' => trim(($t->first_name ?? '') . ' ' . ($t->last_name ?? '')),
                'contact' => $t->phone ?: ($t->email ?: ''),
                'school' => (string) ($t->school ?? ''),
                'qty' => (int) ($t->quantity ?? 0),
                'amount' => (float) ($t->total_amount ?? 0),
                'status' => $status,
                'stkStatus' => (string) ($t->stk_status ?? '—'),
                'paymentDate' => $paymentDate,
                'created' => $created,
            ];
        });

        return response()->json($rows);
    }

    public function statsApi(Request $request)
    {
        $base = [
            'total_tickets' => Ticket::count(),
            'total_paid' => Ticket::where('payment_status', 'completed')->count(),
            'total_pending' => Ticket::where('payment_status', 'pending')->count(),
            'total_failed' => Ticket::where('payment_status', 'failed')->count(),
            'today_sales' => Ticket::where('payment_status', 'completed')->whereDate('payment_date', today())->count(),
        ];

        $user = Auth::user();
        $canViewMetrics = $user && ($user->can('view-metrics') || (method_exists($user, 'hasAnyRole') && $user->hasAnyRole(['super-admin', 'management'])));

        if ($canViewMetrics) {
            $base['total_revenue'] = (float) Ticket::where('payment_status', 'completed')->sum('total_amount');
            $base['today_revenue'] = (float) Ticket::where('payment_status', 'completed')->whereDate('payment_date', today())->sum('total_amount');
            $base['this_month_sales'] = (int) Ticket::where('payment_status', 'completed')->whereMonth('payment_date', now()->month)->whereYear('payment_date', now()->year)->count();
            $base['this_month_revenue'] = (float) Ticket::where('payment_status', 'completed')->whereMonth('payment_date', now()->month)->whereYear('payment_date', now()->year)->sum('total_amount');
        }

        return response()->json($base);
    }

    public function revenueSeriesApi(Request $request)
    {
        $period = $request->get('period', 'daily');
        $user = Auth::user();
        $canViewMetrics = $user && ($user->can('view-metrics') || (method_exists($user, 'hasAnyRole') && $user->hasAnyRole(['super-admin', 'management'])));

        if (!$canViewMetrics) {
            return response()->json(['message' => 'Forbidden'], 403);
        }

        if ($period === 'weekly') {
            $rows = Ticket::where('payment_status', 'completed')
                ->where('payment_date', '>=', now()->subWeeks(8))
                ->selectRaw('YEARWEEK(payment_date, 1) as grp, DATE_FORMAT(payment_date, "%x-W%v") as label, SUM(total_amount) as revenue')
                ->groupBy('grp')
                ->orderBy('grp')
                ->get();
            $labels = $rows->pluck('label')->values();
            $values = $rows->pluck('revenue')->map(fn($v) => (float) $v)->values();
            return response()->json(['labels' => $labels, 'values' => $values]);
        }

        if ($period === 'monthly') {
            $rows = Ticket::where('payment_status', 'completed')
                ->where('payment_date', '>=', now()->subMonths(12))
                ->selectRaw('DATE_FORMAT(payment_date, "%Y-%m") as label, SUM(total_amount) as revenue')
                ->groupBy('label')
                ->orderBy('label')
                ->get();
            $labels = $rows->pluck('label')->values();
            $values = $rows->pluck('revenue')->map(fn($v) => (float) $v)->values();
            return response()->json(['labels' => $labels, 'values' => $values]);
        }

        $rows = Ticket::where('payment_status', 'completed')
            ->where('payment_date', '>=', now()->subDays(30))
            ->selectRaw('DATE(payment_date) as label, SUM(total_amount) as revenue')
            ->groupBy('label')
            ->orderBy('label')
            ->get();
        $labels = $rows->pluck('label')->map(fn($d) => \Carbon\Carbon::parse($d)->format('M j'))->values();
        $values = $rows->pluck('revenue')->map(fn($v) => (float) $v)->values();
        return response()->json(['labels' => $labels, 'values' => $values]);
    }

    public function export(Request $request)
    {
        $status = $request->get('status');
        $event = $request->get('event');
        $school = $request->get('school');
        $stkStatus = $request->get('stk_status');

        $query = Ticket::with('event')
            ->leftJoin(DB::raw('(SELECT ticket_reference_number, stk_status FROM txn_logs WHERE id IN (SELECT MAX(id) FROM txn_logs GROUP BY ticket_reference_number)) as latest_txn'), 'tickets.reference', '=', 'latest_txn.ticket_reference_number')
            ->select('tickets.*', 'latest_txn.stk_status');

        if ($status) {
            $query->where('tickets.payment_status', $status);
        }

        if ($event) {
            $query->where('tickets.event_id', $event);
        }

        if ($school) {
            $query->where('tickets.school', $school);
        }

        if ($stkStatus) {
            $query->where('latest_txn.stk_status', $stkStatus);
        }

        $tickets = $query->orderBy('tickets.created_at', 'desc')->get();

        $filename = 'tickets_export_' . date('Y-m-d_H-i-s') . '.csv';

        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => "attachment; filename=\"{$filename}\"",
        ];

        $callback = function () use ($tickets) {
            $file = fopen('php://output', 'w');

            // CSV headers
            fputcsv($file, [
                'ID',
                'Reference',
                'Event',
                'First Name',
                'Last Name',
                'Phone',
                'Email',
                'School',
                'Quantity',
                'Amount',
                'Total Amount',
                'Payment Status',
                'STK Status',
                'M-Pesa Receipt',
                'Payment Date',
                'Created At'
            ]);

            foreach ($tickets as $ticket) {
                fputcsv($file, [
                    $ticket->id,
                    $ticket->reference,
                    $ticket->event ? $ticket->event->name : 'N/A',
                    $ticket->first_name,
                    $ticket->last_name,
                    $ticket->phone,
                    $ticket->email,
                    $ticket->school,
                    $ticket->quantity,
                    $ticket->amount,
                    $ticket->total_amount,
                    $ticket->payment_status,
                    $ticket->stk_status ?: 'N/A',
                    $ticket->mpesa_receipt_number,
                    $ticket->payment_date ? (is_string($ticket->payment_date) ? $ticket->payment_date : $ticket->payment_date->format('Y-m-d H:i:s')) : '',
                    $ticket->created_at ? $ticket->created_at->format('Y-m-d H:i:s') : '',
                ]);
            }

            fclose($file);
        };

        return response()->stream($callback, 200, $headers);
    }

    public function analytics()
    {
        // Get daily sales for the last 30 days
        $dailySales = Ticket::where('payment_status', 'completed')
            ->where('payment_date', '>=', now()->subDays(30))
            ->selectRaw('DATE(payment_date) as date, COUNT(*) as count, SUM(total_amount) as revenue')
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        // Get sales by school
        $schoolSales = Ticket::where('payment_status', 'completed')
            ->selectRaw('school, COUNT(*) as count, SUM(total_amount) as revenue')
            ->groupBy('school')
            ->orderByDesc('revenue')
            ->limit(10)
            ->get();

        // Get sales by event
        $eventSales = Ticket::where('payment_status', 'completed')
            ->join('events', 'tickets.event_id', '=', 'events.id')
            ->selectRaw('events.name as event_name, COUNT(*) as count, SUM(tickets.total_amount) as revenue')
            ->groupBy('events.id')
            ->orderByDesc('revenue')
            ->get();

        $highlightedEvent = Event::find(1);
        // Get payment status distribution
        $statusDistribution = Ticket::selectRaw('payment_status, COUNT(*) as count')
            ->groupBy('payment_status')
            ->get();

        return view('tickets.layouts.index', compact('dailySales', 'schoolSales', 'eventSales', 'statusDistribution', 'highlightedEvent'));
    }

    public function verifyShow(string $reference)
    {
        $ticket = Ticket::where('reference', $reference)->first();

        if ($ticket) {
            $ticket->is_complimentary = false;
            $ticket->ticket_type = 'Standard';
        } else {
            $ticket = ComplimentaryTicket::where('reference', $reference)->first();
            if ($ticket) {
                // Add virtual attributes to make it compatible with the view
                $ticket->payment_status = 'completed';
                $ticket->payment_date = $ticket->created_at;
                $ticket->total_amount = 0;
                $ticket->is_complimentary = true;
                // ticket_type is already on the model, but let's ensure it's capitalized for display if needed, 
                // or we rely on the view to format 'normal'/'vip'
            }
        }

        $scanCount = $ticket ? DB::table('ticket_scans')->where('ticket_reference', $reference)->count() : 0;
        $lastScan = $ticket ? DB::table('ticket_scans')->where('ticket_reference', $reference)->orderByDesc('created_at')->first() : null;

        return view('ticket.verify', [
            'reference' => $reference,
            'ticket' => $ticket,
            'scanCount' => $scanCount,
            'lastScan' => $lastScan,
            'user' => auth()->user()
        ]);
    }

    public function verifyShowNumber(Request $request)
    {
        $phone = trim($request->input('phone', ''));
        $ticket = null;
        $error = null;
        $reference = null;

        if ($phone) {
            // Normalize phone number (remove +, spaces, hyphens, etc.)
            $normalizedPhone = preg_replace('/[^0-9]/', '', $phone);

            // Get last 9 digits for comparison
            $last9Digits = substr($normalizedPhone, -9);

            // Try to find ticket directly by phone number (using last 9 digits)
            $ticket = Ticket::where(DB::raw('RIGHT(REPLACE(REPLACE(REPLACE(phone, "+", ""), " ", ""), "-", ""), 9)'), $last9Digits)
                ->first();

            // If not found, search in transactions table
            if (!$ticket) {
                // Search transactions where bill_ref_number matches the last 9 digits
                $transaction = Transaction::where(function ($query) use ($last9Digits) {
                    $query->where(DB::raw('RIGHT(REPLACE(REPLACE(REPLACE(bill_ref_number, "+", ""), " ", ""), "-", ""), 9)'), $last9Digits)
                        ->orWhere(DB::raw('RIGHT(REPLACE(REPLACE(REPLACE(msisdn, "+", ""), " ", ""), "-", ""), 9)'), $last9Digits);
                })->first();

                if ($transaction && $transaction->bill_ref_number) {
                    // Get the ticket reference from bill_ref_number
                    $reference = trim($transaction->bill_ref_number);

                    // Find ticket by reference
                    $ticket = Ticket::where('reference', $reference)->first();

                    // If still not found, try to find by phone matching the msisdn last 9 digits
                    if (!$ticket && $transaction->msisdn) {
                        $msisdnLast9 = substr(preg_replace('/[^0-9]/', '', $transaction->msisdn), -9);
                        $ticket = Ticket::where(DB::raw('RIGHT(REPLACE(REPLACE(REPLACE(phone, "+", ""), " ", ""), "-", ""), 9)'), $msisdnLast9)
                            ->first();
                    }
                }
            }

            // Set ticket attributes similar to verifyShow
            if ($ticket) {
                $ticket->is_complimentary = false;
                $ticket->ticket_type = 'Standard';
                $reference = $ticket->reference;
            } else {
                $error = "No ticket found for phone number: {$phone}";
            }
        }

        $scanCount = $ticket && $reference ? DB::table('ticket_scans')->where('ticket_reference', $reference)->count() : 0;
        $lastScan = $ticket && $reference ? DB::table('ticket_scans')->where('ticket_reference', $reference)->orderByDesc('created_at')->first() : null;

        return view('ticket.verify-number', [
            'phone' => $phone,
            'ticket' => $ticket,
            'reference' => $reference,
            'error' => $error,
            'scanCount' => $scanCount,
            'lastScan' => $lastScan,
            'user' => auth()->user()
        ]);
    }

    public function verifyProcess(Request $request)
    {
        $reference = trim($request->input('reference'));
        $user = $request->user();

        $ticket = Ticket::where('reference', $reference)->first();

        if ($ticket) {
            $ticket->is_complimentary = false;
            $ticket->ticket_type = 'Standard';
        } else {
            $ticket = ComplimentaryTicket::where('reference', $reference)->first();
            if ($ticket) {
                // Add virtual attributes
                $ticket->payment_status = 'completed';
                $ticket->payment_date = $ticket->created_at;
                $ticket->is_complimentary = true;
            }
        }

        if (!$ticket || $ticket->payment_status !== 'completed') {
            return view('ticket.verify', [
                'reference' => $reference,
                'ticket' => null,
                'scanCount' => 0,
                'lastScan' => null,
                'user' => $user,
                'status' => 'invalid'
            ]);
        }

        $scanCount = DB::table('ticket_scans')->where('ticket_reference', $reference)->count();
        $lastScan = DB::table('ticket_scans')->where('ticket_reference', $reference)->orderByDesc('created_at')->first();

        if ($scanCount >= $ticket->quantity) {
            return view('ticket.verify', [
                'reference' => $reference,
                'ticket' => $ticket,
                'scanCount' => $scanCount,
                'lastScan' => $lastScan,
                'user' => $user,
                'status' => 'already_scanned'
            ]);
        }

        $verifyAll = $request->boolean('verify_all');
        $targetIndex = (int) $request->input('index', 0);
        $remaining = max(0, $ticket->quantity - $scanCount);

        $toAdd = 0;
        if ($verifyAll) {
            // Verify all remaining tickets
            $toAdd = $remaining;
        } elseif ($targetIndex > 0) {
            // Only allow verifying the next ticket in sequence
            // If scanCount is 0, you can only verify ticket 1
            // If scanCount is 1, you can only verify ticket 2, etc.
            $nextTicketIndex = $scanCount + 1;
            if ($targetIndex == $nextTicketIndex && $remaining > 0) {
                $toAdd = 1;
            }
        } else {
            // No index specified, verify the next one
            if ($remaining > 0) {
                $toAdd = 1;
            }
        }

        if ($toAdd > 0) {
            $rows = [];
            $now = now();
            for ($k = 0; $k < $toAdd; $k++) {
                $rows[] = [
                    'ticket_reference' => $reference,
                    'status' => 'verified',
                    'scanned_by' => $user ? $user->id : null,
                    'created_at' => $now,
                    'updated_at' => $now
                ];
            }
            DB::table('ticket_scans')->insert($rows);
        }

        $scanCount = DB::table('ticket_scans')->where('ticket_reference', $reference)->count();
        $lastScan = DB::table('ticket_scans')->where('ticket_reference', $reference)->orderByDesc('created_at')->first();

        $status = $scanCount >= $ticket->quantity ? 'already_scanned' : 'processed';

        return view('ticket.verify', [
            'reference' => $reference,
            'ticket' => $ticket,
            'scanCount' => $scanCount,
            'lastScan' => $lastScan,
            'user' => $user,
            'status' => $status
        ]);
    }

    public function resendSms(Request $request, $id)
    {
        try {
            $ticket = Ticket::with('event')->findOrFail($id);

            // Format phone number (ensure it starts with 254)
            $phone = trim($ticket->phone);
            if (strpos($phone, '+') === 0) {
                $phone = substr($phone, 1);
            }
            if (strpos($phone, '0') === 0) {
                $phone = '254' . substr($phone, 1);
            }
            if (strpos($phone, '254') !== 0) {
                $phone = '254' . substr($phone, -9);
            }

            // Get event name
            $eventName = $ticket->event ? $ticket->event->name : 'Event';

            // Create SMS message (same format as Homecontroller)
            $message = "Dear {$ticket->first_name} {$ticket->last_name},Welcome to {$eventName}. \nTicket #: {$ticket->reference}  \nTickets: {$ticket->quantity}  \nGet your tickets here:" . url("/get/ticket/{$ticket->reference}");

            // Send SMS using the same method as Homecontroller
            $client = new Client();

            $headers = [
                'Content-Type' => 'application/json',
                'ApiKey' => '2ZqSn5LGPfNyTpvRICWiG3vWnJim6zTR6oXimzg29Isn3niqSrXO8fKrOv4FZDSa',
            ];

            $body = [
                'from' => 'PACESETTER',
                'recipients' => [$phone],
                'message' => $message,
            ];

            $response = $client->post('https://api.wasiliana.com/api/v1/send/sms', [
                'headers' => $headers,
                'json' => $body
            ]);

            $responseData = json_decode($response->getBody(), true);

            Log::info('SMS resent successfully', [
                'ticket_id' => $ticket->id,
                'ticket_reference' => $ticket->reference,
                'recipient' => $phone,
                'response' => $responseData
            ]);

            return response()->json([
                'success' => true,
                'message' => 'SMS sent successfully',
                'data' => [
                    'phone' => $phone,
                    'ticket_reference' => $ticket->reference
                ]
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to resend SMS', [
                'ticket_id' => $id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Failed to send SMS: ' . $e->getMessage()
            ], 500);
        }
    }
}
