<?php

namespace App\Http\Controllers;

use App\Models\MaintenanceInvoice;
use App\Models\MaintenanceLog;
use App\Models\Customer;
use App\Models\Elevator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class MaintenanceInvoiceController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $maintenanceInvoices = MaintenanceInvoice::with(['customer', 'maintenanceLog', 'createdBy'])
            ->orderBy('created_at', 'desc')
            ->paginate(15);

        return view('maintenance.invoices.index', compact('maintenanceInvoices'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $customers = Customer::all();
        $maintenanceLogs = MaintenanceLog::with('elevator')
            ->where('status', 'completed')
            ->whereNull('invoice_id')
            ->get();

        return view('maintenance.invoices.create', compact('customers', 'maintenanceLogs'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'customer_id' => 'required|exists:customers,id',
            'maintenance_log_id' => 'required|exists:maintenance_logs,id',
            'invoice_date' => 'required|date',
            'due_date' => 'required|date|after_or_equal:invoice_date',
            'amount' => 'required|numeric|min:0',
            'tax_rate' => 'required|numeric|min:0|max:100',
            'status' => 'required|in:draft,sent,paid,cancelled',
            'notes' => 'nullable|string',
        ]);

        $maintenanceInvoice = new MaintenanceInvoice();
        $maintenanceInvoice->customer_id = $request->customer_id;
        $maintenanceInvoice->maintenance_log_id = $request->maintenance_log_id;
        $maintenanceInvoice->invoice_date = $request->invoice_date;
        $maintenanceInvoice->due_date = $request->due_date;
        $maintenanceInvoice->amount = $request->amount;
        $maintenanceInvoice->tax_rate = $request->tax_rate;
        $maintenanceInvoice->tax_amount = ($request->amount * $request->tax_rate) / 100;
        $maintenanceInvoice->total_amount = $request->amount + $maintenanceInvoice->tax_amount;
        $maintenanceInvoice->status = $request->status;
        $maintenanceInvoice->notes = $request->notes;
        $maintenanceInvoice->created_by = Auth::id();
        $maintenanceInvoice->save();

        // Update the maintenance log with the invoice ID
        $maintenanceLog = MaintenanceLog::find($request->maintenance_log_id);
        $maintenanceLog->invoice_id = $maintenanceInvoice->id;
        $maintenanceLog->save();

        return redirect()->route('maintenance-invoices.index')
            ->with('success', 'تم إنشاء فاتورة الصيانة بنجاح');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\MaintenanceInvoice  $maintenanceInvoice
     * @return \Illuminate\Http\Response
     */
    public function show(MaintenanceInvoice $maintenanceInvoice)
    {
        $maintenanceInvoice->load(['customer', 'maintenanceLog.elevator', 'createdBy']);

        return view('maintenance.invoices.show', compact('maintenanceInvoice'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\MaintenanceInvoice  $maintenanceInvoice
     * @return \Illuminate\Http\Response
     */
    public function edit(MaintenanceInvoice $maintenanceInvoice)
    {
        $customers = Customer::all();
        $maintenanceLogs = MaintenanceLog::with('elevator')
            ->where('status', 'completed')
            ->where(function ($query) use ($maintenanceInvoice) {
                $query->whereNull('invoice_id')
                    ->orWhere('invoice_id', $maintenanceInvoice->id);
            })
            ->get();

        return view('maintenance.invoices.edit', compact('maintenanceInvoice', 'customers', 'maintenanceLogs'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\MaintenanceInvoice  $maintenanceInvoice
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, MaintenanceInvoice $maintenanceInvoice)
    {
        $request->validate([
            'customer_id' => 'required|exists:customers,id',
            'maintenance_log_id' => 'required|exists:maintenance_logs,id',
            'invoice_date' => 'required|date',
            'due_date' => 'required|date|after_or_equal:invoice_date',
            'amount' => 'required|numeric|min:0',
            'tax_rate' => 'required|numeric|min:0|max:100',
            'status' => 'required|in:draft,sent,paid,cancelled',
            'notes' => 'nullable|string',
        ]);

        // If maintenance log has changed, update the old one
        if ($maintenanceInvoice->maintenance_log_id != $request->maintenance_log_id) {
            $oldLog = MaintenanceLog::find($maintenanceInvoice->maintenance_log_id);
            if ($oldLog) {
                $oldLog->invoice_id = null;
                $oldLog->save();
            }
        }

        $maintenanceInvoice->customer_id = $request->customer_id;
        $maintenanceInvoice->maintenance_log_id = $request->maintenance_log_id;
        $maintenanceInvoice->invoice_date = $request->invoice_date;
        $maintenanceInvoice->due_date = $request->due_date;
        $maintenanceInvoice->amount = $request->amount;
        $maintenanceInvoice->tax_rate = $request->tax_rate;
        $maintenanceInvoice->tax_amount = ($request->amount * $request->tax_rate) / 100;
        $maintenanceInvoice->total_amount = $request->amount + $maintenanceInvoice->tax_amount;
        $maintenanceInvoice->status = $request->status;
        $maintenanceInvoice->notes = $request->notes;
        $maintenanceInvoice->save();

        // Update the new maintenance log with the invoice ID
        $maintenanceLog = MaintenanceLog::find($request->maintenance_log_id);
        $maintenanceLog->invoice_id = $maintenanceInvoice->id;
        $maintenanceLog->save();

        return redirect()->route('maintenance-invoices.index')
            ->with('success', 'تم تحديث فاتورة الصيانة بنجاح');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\MaintenanceInvoice  $maintenanceInvoice
     * @return \Illuminate\Http\Response
     */
    public function destroy(MaintenanceInvoice $maintenanceInvoice)
    {
        // Update the maintenance log to remove the invoice ID
        $maintenanceLog = MaintenanceLog::find($maintenanceInvoice->maintenance_log_id);
        if ($maintenanceLog) {
            $maintenanceLog->invoice_id = null;
            $maintenanceLog->save();
        }

        $maintenanceInvoice->delete();

        return redirect()->route('maintenance-invoices.index')
            ->with('success', 'تم حذف فاتورة الصيانة بنجاح');
    }

    /**
     * Print the invoice.
     *
     * @param  \App\Models\MaintenanceInvoice  $maintenanceInvoice
     * @return \Illuminate\Http\Response
     */
    public function print(MaintenanceInvoice $maintenanceInvoice)
    {
        $maintenanceInvoice->load(['customer', 'maintenanceLog.elevator', 'maintenanceLog.technician', 'createdBy']);
        $company = Auth::user()->company;

        return view('maintenance.invoices.print', compact('maintenanceInvoice', 'company'));
    }

    /**
     * Send the invoice by email.
     *
     * @param  \App\Models\MaintenanceInvoice  $maintenanceInvoice
     * @return \Illuminate\Http\Response
     */
    public function send(MaintenanceInvoice $maintenanceInvoice)
    {
        $maintenanceInvoice->load(['customer', 'maintenanceLog.elevator', 'createdBy']);

        // Check if customer has email
        if (!$maintenanceInvoice->customer->email) {
            return redirect()->back()->with('error', 'لا يوجد بريد إلكتروني للعميل');
        }

        // Send email logic here
        // For now, just update the status to 'sent'
        $maintenanceInvoice->status = 'sent';
        $maintenanceInvoice->save();

        return redirect()->route('maintenance-invoices.show', $maintenanceInvoice->id)
            ->with('success', 'تم إرسال الفاتورة بنجاح');
    }

    /**
     * Mark the invoice as paid.
     *
     * @param  \App\Models\MaintenanceInvoice  $maintenanceInvoice
     * @return \Illuminate\Http\Response
     */
    public function markAsPaid(MaintenanceInvoice $maintenanceInvoice)
    {
        $maintenanceInvoice->status = 'paid';
        $maintenanceInvoice->save();

        return redirect()->route('maintenance-invoices.show', $maintenanceInvoice->id)
            ->with('success', 'تم تحديث حالة الفاتورة إلى مدفوعة');
    }

    /**
     * Mark the invoice as cancelled.
     *
     * @param  \App\Models\MaintenanceInvoice  $maintenanceInvoice
     * @return \Illuminate\Http\Response
     */
    public function markAsCancelled(MaintenanceInvoice $maintenanceInvoice)
    {
        $maintenanceInvoice->status = 'cancelled';
        $maintenanceInvoice->save();

        return redirect()->route('maintenance-invoices.show', $maintenanceInvoice->id)
            ->with('success', 'تم تحديث حالة الفاتورة إلى ملغاة');
    }
}
