<?php

namespace App\Http\Controllers;

use App\Models\Invoices;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class InvoicesController extends Controller
{
    // public function index()
    // {
    //     try {
    //         $invoices = Invoices::with(['customer', 'plan', 'transaction'])
    //             ->latest()
    //             ->paginate(10);

    //         return response()->json([
    //             'success' => true,
    //             'data'    => $invoices,
    //         ], 200);

    //     } catch (\Throwable $e) {
    //         Log::error('Invoice index failed', [
    //             'error' => $e->getMessage(),
    //         ]);

    //         return response()->json([
    //             'success' => false,
    //             'message' => 'Failed to fetch invoices',
    //         ], 500);
    //     }
    // }

    public function show(Request $request)
    {
        try {
            /** -------------------------
             * Auth Token
             * ------------------------- */
            $enc_token = $request->bearerToken();
            if (!$enc_token) {
                return response()->json([
                    'success' => false,
                    'message' => 'Missing auth token'
                ], 401);
            }

            try {
                $customer_id = Crypt::decrypt($enc_token);
            } catch (\Throwable $e) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid auth token'
                ], 401);
            }

            $invoice = Invoices::where([
                'invoice_number' => $request->invoice_number,
                'customer_id'    => $customer_id,
            ])->first();

            if (!$invoice) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invoice not found',
                ], 404);
            }

            if (!$invoice->file_path) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invoice PDF not generated yet',
                ], 404);
            }

            if (!Storage::disk('public')->exists($invoice->file_path)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invoice PDF not found',
                ], 404);
            }

            return response()->file(
                storage_path("app/public/{$invoice->file_path}"),
                [
                    'Content-Type'        => 'application/pdf',
                    'Content-Disposition' => 'inline; filename="' . basename($invoice->file_path) . '"',
                ]
            );
        } catch (DecryptException $e) {

            return response()->json([
                'success' => false,
                'message' => 'Invalid invoice ID',
            ], 400);
        } catch (ModelNotFoundException $e) {

            return response()->json([
                'success' => false,
                'message' => 'Invoice not found',
            ], 404);
        } catch (\Throwable $e) {

            Log::error('Invoice show failed', [
                'error'             => $e->getMessage(),
                'invoice_number'    => $request->invoice_number,
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Failed to load invoice',
            ], 500);
        }
    }

    public function download($id)
    {
        try {
            $inv_id = Crypt::decrypt($id);

            $invoice = Invoices::findOrFail($inv_id);

            if (!$invoice->file_path) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invoice PDF not generated yet',
                ], 404);
            }

            if (!Storage::disk('public')->exists($invoice->file_path)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invoice PDF not found',
                ], 404);
            }

            return response()->download(
                storage_path("app/public/{$invoice->file_path}"),
                basename($invoice->file_path)
            );
        } catch (DecryptException $e) {

            return response()->json([
                'success' => false,
                'message' => 'Invalid invoice ID',
            ], 400);
        } catch (ModelNotFoundException $e) {

            return response()->json([
                'success' => false,
                'message' => 'Invoice not found',
            ], 404);
        } catch (\Throwable $e) {

            Log::error('Invoice download failed', [
                'error' => $e->getMessage(),
                'id'    => $id,
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Failed to download invoice',
            ], 500);
        }
    }
}
