<?php

namespace Modules\Vrc\Http\Controllers;

use Illuminate\Http\Request;
use Modules\Vrc\Entities\VrcEstimate;
use Modules\Vrc\Entities\VrcEstimateItem;
use Modules\Vrc\Entities\VrcRepairOrder;
use Modules\Vrc\Services\Contracts\ContactServiceContract;
use Modules\Vrc\Services\Estimate\EstimateService;
use Yajra\DataTables\Facades\DataTables;

class EstimateController extends VrcBaseController
{
    public function __construct(
        protected EstimateService $estimates,
        protected ContactServiceContract $contacts
    ) {
    }

    public function index()
    {
        $this->guard('vrc.estimate.view');

        if (request()->ajax()) {
            $rows = VrcEstimate::where('vrc_estimates.business_id', $this->businessId())
                ->leftJoin('contacts as c', 'c.id', '=', 'vrc_estimates.erp_customer_id')
                ->select(['vrc_estimates.id', 'vrc_estimates.number', 'vrc_estimates.status', 'vrc_estimates.grand_total', 'vrc_estimates.valid_until', 'c.name as customer_name']);

            return DataTables::of($rows)
                ->editColumn('number', fn ($r) => $r->number ?: ('#' . $r->id))
                ->editColumn('status', fn ($r) => '<span class="label label-default">' . __('vrc::lang.est_status_' . $r->status) . '</span>')
                ->addColumn('action', fn ($r) => '<a href="' . route('vrc.estimates.show', $r->id) . '" class="btn btn-xs btn-primary"><i class="fa fa-eye"></i> ' . __('messages.view') . '</a>')
                ->rawColumns(['status', 'action'])
                ->make(true);
        }

        return view('vrc::estimates.index');
    }

    /** Build an estimate from a repair order. */
    public function createFromRo($repairOrderId)
    {
        $this->guard('vrc.estimate.manage');
        $ro = VrcRepairOrder::with('services')->where('business_id', $this->businessId())->findOrFail($repairOrderId);

        $estimate = $this->estimates->createFromRepairOrder($ro, $this->userId());

        return redirect()->route('vrc.estimates.show', $estimate->id);
    }

    public function show($id)
    {
        $this->guard('vrc.estimate.view');
        $estimate = VrcEstimate::with('items')->where('business_id', $this->businessId())->findOrFail($id);
        $customer = $this->contacts->find($this->businessId(), (int) $estimate->erp_customer_id);

        return view('vrc::estimates.show', [
            'estimate' => $estimate,
            'customer' => $customer,
            'taxRates' => \App\TaxRate::forBusinessDropdown($this->businessId(), true)['tax_rates'],
        ]);
    }

    public function addItem(Request $request, $id)
    {
        $this->guard('vrc.estimate.manage');
        $estimate = VrcEstimate::where('business_id', $this->businessId())->findOrFail($id);
        $data = $this->validate($request, [
            'kind'        => 'required|in:service,part',
            'description' => 'required|string|max:255',
            'qty'         => 'nullable|numeric|min:0',
            'unit_price'  => 'nullable|numeric|min:0',
            'discount'    => 'nullable|numeric|min:0',
            'tax_rate_id' => 'nullable|integer',
        ]);

        try {
            VrcEstimateItem::create(array_merge($data, [
                'business_id' => $estimate->business_id,
                'estimate_id' => $estimate->id,
                'qty'         => $data['qty'] ?? 1,
                'unit_price'  => $data['unit_price'] ?? 0,
                'discount'    => $data['discount'] ?? 0,
            ]));
            $this->estimates->recompute($estimate);
            return $this->ok(__('vrc::lang.added_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());
            return $this->fail();
        }
    }

    public function removeItem($id, $item)
    {
        $this->guard('vrc.estimate.manage');
        $estimate = VrcEstimate::where('business_id', $this->businessId())->findOrFail($id);
        try {
            VrcEstimateItem::where('estimate_id', $estimate->id)->where('id', $item)->delete();
            $this->estimates->recompute($estimate);
            return $this->ok(__('vrc::lang.deleted_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());
            return $this->fail();
        }
    }

    /** Mark sent: generate the tokenized approval link (returned to the UI). */
    public function send($id)
    {
        $this->guard('vrc.estimate.manage');
        $estimate = VrcEstimate::where('business_id', $this->businessId())->findOrFail($id);

        try {
            $this->estimates->send($estimate, $this->userId());
            $link = route('vrc.portal.estimate', $estimate->approval_token);
            // NOTE: actual email/SMS/WhatsApp dispatch is wired via the ERP
            // notification system in Phase 11 (comms matrix). Here we surface
            // the working approval link + PDF.
            return $this->ok(__('vrc::lang.estimate_sent'), ['link' => $link]);
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());
            return $this->fail();
        }
    }

    /** Advisor-recorded approval (portal approval handled separately). */
    public function approve(Request $request, $id)
    {
        $this->guard('vrc.estimate.approve');
        $estimate = VrcEstimate::where('business_id', $this->businessId())->findOrFail($id);

        try {
            $this->estimates->approve($estimate, $this->userId(), $request->get('method', 'in_person'), $this->userId());
            return $this->ok(__('vrc::lang.estimate_approved'));
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    public function decline(Request $request, $id)
    {
        $this->guard('vrc.estimate.manage');
        $estimate = VrcEstimate::where('business_id', $this->businessId())->findOrFail($id);
        try {
            $this->estimates->decline($estimate, $this->userId(), $request->get('method', 'in_person'), $request->get('reason'));
            return $this->ok(__('vrc::lang.estimate_declined'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());
            return $this->fail();
        }
    }

    /** Render the estimate as a PDF via the ERP mPDF mechanism. */
    public function pdf($id)
    {
        $this->guard('vrc.estimate.view');
        $estimate = VrcEstimate::with('items')->where('business_id', $this->businessId())->findOrFail($id);
        $customer = $this->contacts->find($this->businessId(), (int) $estimate->erp_customer_id);

        $html = view('vrc::estimates.pdf', compact('estimate', 'customer'))->render();

        $mpdf = $this->getMpdf();
        $mpdf->WriteHTML($html);

        return $mpdf->Output(($estimate->number ?: 'estimate') . '.pdf', 'I');
    }
}
