<?php

namespace App\Livewire\Admin;

use Livewire\Component;
use Livewire\WithPagination;
use Livewire\Attributes\Layout;
use App\Models\Lead;
use Illuminate\Support\Facades\Storage;

#[Layout('components.admin-layout')]
class Leads extends Component
{
    use WithPagination;

    public $search = '';
    public $sourceFilter = '';
    public $perPage = 10;
    public $sortField = 'created_at';
    public $sortDirection = 'desc';

    // View modal properties
    public $showViewModal = false;
    public $viewingLead = null;

    public function sortBy($field)
    {
        if ($this->sortField === $field) {
            $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortField = $field;
            $this->sortDirection = 'asc';
        }
    }

    public function viewLead($leadId)
    {
        $this->viewingLead = Lead::findOrFail($leadId);
        $this->showViewModal = true;
    }

    public function closeViewModal()
    {
        $this->showViewModal = false;
        $this->viewingLead = null;
    }

    public function deleteLead($leadId)
    {
        $lead = Lead::findOrFail($leadId);
        
        // Delete permit document if exists
        if ($lead->permit_doc && Storage::disk('public')->exists($lead->permit_doc)) {
            Storage::disk('public')->delete($lead->permit_doc);
        }
        
        $lead->delete();
        
        session()->flash('success', 'Lead deleted successfully.');
    }

    public function downloadPermitDoc($leadId)
{
    $lead = Lead::findOrFail($leadId);
    
    if (!$lead->permit_doc || !Storage::disk('public')->exists($lead->permit_doc)) {
        session()->flash('error', 'Document not found.');
        return;
    }
    
    $filePath = Storage::disk('public')->path($lead->permit_doc);
    $fileName = 'permit_document_' . $lead->firstname . '_' . $lead->lastname . '.' . pathinfo($filePath, PATHINFO_EXTENSION);
    
    return response()->download($filePath, $fileName);
}

    public function getSourcesProperty()
    {
        return Lead::distinct()->pluck('source')->filter();
    }

    public function render()
    {
        $leads = Lead::query()
            ->when($this->search, function ($query) {
                $query->where(function ($q) {
                    $q->where('firstname', 'like', '%' . $this->search . '%')
                      ->orWhere('lastname', 'like', '%' . $this->search . '%')
                      ->orWhere('email', 'like', '%' . $this->search . '%')
                      ->orWhere('companyname', 'like', '%' . $this->search . '%')
                      ->orWhere('phone', 'like', '%' . $this->search . '%');
                });
            })
            ->when($this->sourceFilter, function ($query) {
                $query->where('source', $this->sourceFilter);
            })
            ->orderBy($this->sortField, $this->sortDirection)
            ->paginate($this->perPage);

        return view('livewire.admin.leads', [
            'leads' => $leads,
            'sources' => $this->sources,
        ]);
    }
}