<?php

namespace App\Http\Controllers;

use App\Models\Client;
use App\Models\Payment;
use App\Models\LockerRegistration;
use App\Models\Company;
use App\Services\InvoicePdfGenerator;
use Illuminate\Http\Request;

class InvoiceController extends Controller
{
    public function index(Request $request)
    {
        $query = Payment::with(['registration.client', 'registration.locker', 'registration.items'])
            ->orderBy('payment_date', 'desc');

        // Search by invoice number or client name
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('id', 'like', "%{$search}%")
                  ->orWhereHas('registration.client', function ($clientQuery) use ($search) {
                      $clientQuery->where('name', 'like', "%{$search}%")
                                  ->orWhere('phone', 'like', "%{$search}%");
                  })
                  ->orWhereHas('registration.items', function ($itemQuery) use ($search) {
                      $itemQuery->where('locker_number', 'like', "%{$search}%")
                                ->orWhere('total_amount', 'like', "%{$search}%");
                  });
            });
        }

        // Filter by status
        if ($request->filled('status') && in_array($request->status, ['paid', 'partial', 'pending'])) {
            $query->where('status', $request->status);
        }

        // Filter by payment type (notes: create, add, renewal)
        if ($request->filled('payment_type') && in_array($request->payment_type, ['create', 'add', 'renewal'])) {
            $query->where('notes', $request->payment_type);
        }

        // Filter by date range
        if ($request->filled('from_date')) {
            $query->whereDate('payment_date', '>=', $request->from_date);
        }
        if ($request->filled('to_date')) {
            $query->whereDate('payment_date', '<=', $request->to_date);
        }

        $invoices = $query->paginate(15)->withQueryString();

        // Summary statistics by payment type
        $totalInvoices = Payment::count();
        $paidAmount = Payment::where('status', 'paid')->sum('total_amount');
        $createCount = Payment::where('notes', 'create')->count();
        $addCount = Payment::where('notes', 'add')->count();
        $renewalCount = Payment::where('notes', 'renewal')->count();

        return view('invoices.index', compact(
            'invoices',
            'totalInvoices',
            'paidAmount',
            'createCount',
            'addCount',
            'renewalCount'
        ));
    }
    
    // Show invoice as HTML
    // public function show($clientId, $registrationId)
    // {
    //     $client = Client::with('cityRel', 'stateRel', 'countryRel')->findOrFail($clientId);
    //     $registration = LockerRegistration::with('items', 'locker', 'membershipPlan', 'payments')
    //         ->findOrFail($registrationId);
        
    //     // Get payment if exists, otherwise create a dummy payment object for display
    //     $payment = $registration->payments->first();
    //     if (!$payment) {
    //         // Create a dummy payment object for display purposes
    //         $payment = new \stdClass();
    //         $payment->id = 'INV-' . $registration->id;
    //         $payment->payment_date = $registration->registration_date;
    //         $payment->total_amount = $registration->items->sum('amount') + ($registration->tax_amount ?? 0) + ($registration->stamping_fee ?? 0) + ($registration->key_deposit ?? 0) + ($registration->insurance_charges ?? 0) - ($registration->discount_amount ?? 0);
    //         $payment->status = 'generated';
    //     }
        
        
    //     return view('invoices.show', compact('client', 'payment', 'registration'));
    // }

    public function show($paymentId)
    {
        // Get payment with related registration and client
        $payment = Payment::with(['registration.client', 'registration.items', 'registration.locker', 'registration.membershipPlan'])
            ->findOrFail($paymentId);
 
        $registration = $payment->registration;
        $client = $registration->client;
        
        return view('invoices.show', compact('client', 'payment', 'registration'));
    }

    // Download invoice as PDF using native PHP
    public function download($clientId, $registrationId)
    {
        $client = Client::findOrFail($clientId);
        $registration = LockerRegistration::with('items', 'locker', 'membershipPlan', 'payments')
            ->findOrFail($registrationId);
        
        // Get payment if exists, otherwise create a dummy payment object for display
        $payment = $registration->payments->first();
        if (!$payment) {
            // Create a dummy payment object for display purposes
            $payment = new \stdClass();
            $payment->id = 'INV-' . $registration->id;
            $payment->payment_date = $registration->registration_date;
            $payment->total_amount = $registration->items->sum('amount') + ($registration->tax_amount ?? 0) + ($registration->stamping_fee ?? 0) + ($registration->key_deposit ?? 0) + ($registration->insurance_charges ?? 0) - ($registration->discount_amount ?? 0);
            $payment->status = 'generated';
        }

        // Get company information
        $company = Company::active()->first();
        if (!$company) {
            // Use static company information if no company record exists
            $companyData = [
                'name' => 'May Safe Box',
                'address' => '123 Business Street',
                'city' => 'Chennai',
                'state' => 'Tamil Nadu',
                'pincode' => '600001',
                'gst_number' => 'GSTIN1234567890',
                'phone_number' => '+91 98765 43210'
            ];
        } else {
            $companyData = [
                'name' => $company->name,
                'address' => $company->address,
                'city' => $company->city,
                'state' => $company->state,
                'pincode' => $company->pincode,
                'gst_number' => $company->gst_number,
                'phone_number' => '+91 98765 43210' // Static phone if not in company model
            ];
        }

        // Prepare data for PDF
        $data = [
            'company' => $companyData,
            'invoice_number' => $payment->id,
            'date' => $payment->payment_date ? \Carbon\Carbon::parse($payment->payment_date)->format('d-m-Y') : now()->format('d-m-Y'),
            'client_name' => $client->name,
            'client_phone' => $client->phone,
            'client_address' => $client->address . ', ' . $client->city . ', ' . $client->state . ', ' . $client->country,
            'registration_id' => $registration->id,
            'membership_plan' => $registration->membershipPlan->name ?? 'N/A',
            'contract_period' => $registration->contract_start_date . ' to ' . $registration->contract_end_date,
            'items' => $registration->items->map(function($item) {
                return [
                    'locker_number' => $item->locker_number,
                    'size' => $item->size,
                    'type' => $item->type,
                    'amount' => $item->amount
                ];
            })->toArray(),
            'total_amount' => $payment->total_amount
        ];

        // Generate PDF using InvoicePdfGenerator
        $pdfGenerator = new InvoicePdfGenerator();
        $pdfContent = $pdfGenerator->generate($client, $payment, $registration);

        // Return PDF as download
        return response($pdfContent)
            ->header('Content-Type', 'application/pdf')
            ->header('Content-Disposition', 'attachment; filename="invoice_' . $payment->id . '.pdf"')
            ->header('Content-Length', strlen($pdfContent));
    }
}
