<?php

namespace App\Livewire\CustomerPortal;

use App\Models\JobCard;
use App\Models\Estimate;
use App\Services\WorkflowService;
use Livewire\Component;

class EstimateView extends Component
{
    public JobCard $jobCard;
    public Estimate $estimate;
    public $customerComments = '';

    public function mount(JobCard $jobCard, Estimate $estimate)
    {
        $this->jobCard = $jobCard->load(['customer', 'vehicle']);
        $this->estimate = $estimate->load(['lineItems', 'diagnosis']);
        
        // Mark estimate as viewed
        if ($estimate->status === 'sent') {
            $estimate->update(['status' => 'viewed']);
        }
    }

    public function approveEstimate()
    {
        $workflowService = app(WorkflowService::class);
        
        $this->estimate->update([
            'customer_approval_status' => 'approved',
            'customer_approved_at' => now(),
            'customer_approval_method' => 'portal',
            'status' => 'approved',
        ]);

        $this->jobCard->update(['status' => 'estimate_approved']);

        // Notify relevant staff
        $workflowService->notifyStaffOfApproval($this->estimate);

        session()->flash('message', 'Estimate approved successfully! We will begin work on your vehicle soon.');
        
        return redirect()->route('customer-portal.status', $this->jobCard);
    }

    public function rejectEstimate()
    {
        $this->validate([
            'customerComments' => 'required|string|max:1000'
        ]);

        $this->estimate->update([
            'customer_approval_status' => 'rejected',
            'customer_approved_at' => now(),
            'customer_approval_method' => 'portal',
            'status' => 'rejected',
            'notes' => $this->customerComments,
        ]);

        $this->jobCard->update(['status' => 'estimate_rejected']);

        session()->flash('message', 'Estimate rejected. Our team will contact you to discuss alternatives.');
        
        return redirect()->route('customer-portal.status', $this->jobCard);
    }

    public function render()
    {
        return view('livewire.customer-portal.estimate-view');
    }
}
