<?php

namespace Modules\Vrc\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\Vrc\Entities\VrcEstimate;
use Modules\Vrc\Services\Estimate\EstimateService;

/**
 * Public, tokenized estimate approval (spec §6.6) — no login required. The
 * customer opens a signed link, reviews the quote, and approves or declines.
 * Rate-limited at the route level.
 */
class PortalEstimateController extends Controller
{
    public function __construct(protected EstimateService $estimates)
    {
    }

    public function show($token)
    {
        $estimate = VrcEstimate::with('items')->where('approval_token', $token)->firstOrFail();
        $customer = \App\Contact::find($estimate->erp_customer_id);

        return view('vrc::portal.estimate', compact('estimate', 'customer'));
    }

    public function approve($token)
    {
        $estimate = VrcEstimate::where('approval_token', $token)->firstOrFail();

        if (! in_array($estimate->status, ['sent', 'draft'])) {
            return redirect()->route('vrc.portal.estimate', $token)
                ->with('vrc_msg', __('vrc::lang.estimate_already_decided'));
        }

        try {
            $this->estimates->approve($estimate, null, 'portal');
            return redirect()->route('vrc.portal.estimate', $token)->with('vrc_msg', __('vrc::lang.estimate_thanks_approved'));
        } catch (\Exception $e) {
            return redirect()->route('vrc.portal.estimate', $token)->with('vrc_msg', $e->getMessage());
        }
    }

    public function decline(Request $request, $token)
    {
        $estimate = VrcEstimate::where('approval_token', $token)->firstOrFail();

        if (! in_array($estimate->status, ['sent', 'draft'])) {
            return redirect()->route('vrc.portal.estimate', $token)->with('vrc_msg', __('vrc::lang.estimate_already_decided'));
        }

        $this->estimates->decline($estimate, null, 'portal', $request->get('reason'));

        return redirect()->route('vrc.portal.estimate', $token)->with('vrc_msg', __('vrc::lang.estimate_thanks_declined'));
    }
}
