<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Invoice;
use App\Models\Brand;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class InvoiceController extends Controller
{
    public function create()
    {
        $brands = Brand::where('status', 1)->get();
        return view('dashboard.invoices-create', compact('brands'));
    }

    public function store(Request $request)
    {
        // Debugging - request data check
        \Log::info('Invoice Store Request:', $request->all());

        // Validate the request
        $validated = $request->validate([
            'amount' => 'required|numeric|min:0',
            'brand_id' => 'required|exists:brands,id',
            'due_date' => 'required|date|after:today',
            'status' => 'required|boolean',
            'payment_status' => 'required|in:unpaid,pending,paid',
            'customer_name' => 'required|string|max:255',
            'customer_number' => 'nullable|string|max:20',
            'customer_email' => 'nullable|email|max:255',
            'customer_address' => 'nullable|string',
            'description' => 'nullable|string',
        ]);

        try {
            DB::beginTransaction();

            // Create invoice number
            $invoiceCount = Invoice::count() + 1;
            $invoiceNumber = 'INV-' . date('Ymd') . '-' . str_pad($invoiceCount, 4, '0', STR_PAD_LEFT);

            // Create invoice
            $invoice = Invoice::create([
                'invoice_number' => $invoiceNumber,
                'amount' => $validated['amount'],
                'brand_id' => $validated['brand_id'],
                'due_date' => $validated['due_date'],
                'status' => $validated['status'],
                'payment_status' => $validated['payment_status'],
                'customer_name' => $validated['customer_name'],
                'customer_number' => $validated['customer_number'],
                'customer_email' => $validated['customer_email'],
                'customer_address' => $validated['customer_address'],
                'description' => $validated['description'],
            ]);

            DB::commit();

            \Log::info('Invoice Created Successfully:', $invoice->toArray());

            return response()->json([
                'success' => true,
                'message' => 'Invoice created successfully!',
                'invoice' => $invoice
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('Invoice Creation Error: ' . $e->getMessage());

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

    public function index(Request $request)
    {
        $query = Invoice::with('brand')->latest();

        if ($request->has('search') && $request->search != '') {
            $search = $request->search;
            $query->where('invoice_number', 'like', '%' . $search . '%')
                  ->orWhere('customer_name', 'like', '%' . $search . '%');
        }
        $invoices = $query->get();
        $brands = Brand::where('status', 1)->get(); // Fetch brands
        return view('dashboard.invoices', compact('invoices', 'brands'));
    }

    /**
     * Display the specified invoice.
     *
     * @param  \App\Models\Invoice  $invoice
     * @return \Illuminate\View\View
     */
    public function show(Invoice $invoice)
    {
        return view('dashboard.invoices-show', compact('invoice'));
    }

    /**
     * Display the specified invoice publicly.
     *
     * @param  \App\Models\Invoice  $invoice
     * @return \Illuminate\View\View
     */
    public function publicShow(Invoice $invoice)
    {
        // You might want to add a check here to ensure only 'active' invoices are viewable publicly.
        return view('dashboard.public-show', compact('invoice'));
    }

    /**
     * Show the form for editing the specified invoice.
     *
     * @param  \App\Models\Invoice  $invoice
     * @return \Illuminate\View\View
     */
    public function edit(Invoice $invoice)
    {
        $brands = Brand::where('status', 1)->get();
        return view('dashboard.invoices-edit', compact('invoice', 'brands'));
    }

    /**
     * Update the specified invoice in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Invoice  $invoice
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, Invoice $invoice)
    {
        $prefix = auth()->user()->role === 'admin' ? 'admin.' : 'user.';

        $validated = $request->validate([
            'amount' => 'required|numeric|min:0',
            'brand_id' => 'required|exists:brands,id',
            'due_date' => 'required|date',
            'status' => 'required|boolean',
            'payment_status' => 'required|in:unpaid,pending,paid',
            'customer_name' => 'required|string|max:255',
            'customer_number' => 'nullable|string|max:20',
            'customer_email' => 'nullable|email|max:255',
            'customer_address' => 'nullable|string',
            'description' => 'nullable|string',
        ]);

        $invoice->update($validated);

        return redirect()->route($prefix . 'invoices.index')->with('success', 'Invoice updated successfully.');
    }

    /**
     * Remove the specified invoice from storage.
     *
     * @param  \App\Models\Invoice  $invoice
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(Invoice $invoice)
    {
        $prefix = auth()->user()->role === 'admin' ? 'admin.' : 'user.';

        try {
            $invoice->delete();
            return redirect()->route($prefix . 'invoices.index')->with('success', 'Invoice deleted successfully.');
        } catch (\Exception $e) {
            \Log::error('Invoice deletion error: ' . $e->getMessage());
            return redirect()->route($prefix . 'invoices.index')->with('error', 'Failed to delete invoice.');
        }
    }

    public function changeStatus(Request $request)
    {
        $validated = $request->validate([
            'id' => 'required|exists:invoices,id',
            'status' => 'required|boolean',
        ]);

        try {
            $invoice = Invoice::findOrFail($validated['id']);
            $invoice->status = $validated['status'];
            $invoice->save();

            return response()->json([
                'success' => true,
                'message' => 'Invoice status updated successfully!',
            ]);
        } catch (\Exception $e) {
            \Log::error('Invoice status update error: ' . $e->getMessage());
            return response()->json(['success' => false, 'message' => 'Failed to update status.'], 500);
        }
    }

    /**
     * Toggle the status of an invoice via AJAX.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function toggleStatus(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required|exists:invoices,id',
            'status' => 'required|boolean',
        ]);

        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        try {
            $invoice = Invoice::findOrFail($request->input('id'));
            $invoice->status = $request->input('status');
            $invoice->save();

            return response()->json(['message' => 'Invoice status updated successfully.']);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Failed to update invoice status.'], 500);
        }
    }
}