<?php

namespace App\Http\Controllers;

use App\Exports\LeadsExport;
use App\Models\Account;
use App\Models\Lead;
use App\Models\LeadCallback;
use App\Models\LeadEmail;
use App\Models\LeadFollowup;
use App\Models\LeadNote;
use App\Models\LeadPhone;
use App\Models\LeadSale;
use App\Models\LeadService;
use App\Models\User;
use App\Services\LeadImportService;
use App\Traits\ApiResponse;
use App\Traits\ResolvesAccessibleUserIds;
use Dompdf\Dompdf;
use Illuminate\Support\Facades\Storage;
use Dompdf\Options;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Maatwebsite\Excel\Facades\Excel;

class LeadController extends Controller
{
    use ApiResponse, ResolvesAccessibleUserIds;

    private function leadRelations(): array
    {
        return [
            'company:id,name,logo',
            'creator:id,name,image_path',
            'assignee:id,name,image_path',
            'phones:id,lead_id,country_code,phone,is_primary',
            'emails:id,lead_id,email,is_primary',
        ];
    }

    private function formatLead(Lead $lead): array
    {
        $lead->loadMissing($this->leadRelations());

        return [
            'id' => $lead->id,
            'company' => $lead->company ? [
                'id' => $lead->company->id,
                'name' => $lead->company->name,
                'logo' => $lead->company->logo
                    ? Storage::disk('public')->url($lead->company->logo)
                    : null,
            ] : null,
            'name' => $lead->name,
            'email' => $lead->email,
            'country_code' => $lead->country_code,
            'phone' => $lead->phone,
            'emails' => $lead->emails->sortByDesc('is_primary')->values()->map(fn ($email) => [
                'id' => $email->id,
                'email' => $email->email,
                'is_primary' => (int) $email->is_primary,
            ])->values(),
            'phones' => $lead->phones->sortByDesc('is_primary')->values()->map(fn ($phone) => [
                'id' => $phone->id,
                'country_code' => $phone->country_code,
                'phone' => $phone->phone,
                'is_primary' => (int) $phone->is_primary,
            ])->values(),
            'source' => $lead->source,
            'priority' => $lead->priority,
            'status' => $lead->status,
            'is_interest' => $lead->is_interest,
            'is_call_back' => $lead->is_call_back,
            'is_primary' => $lead->is_primary,
            'cnvt_to_verified_at' => $lead->cnvt_to_verified_at,
            'cnvt_to_client_at' => $lead->cnvt_to_client_at,
            'created_by' => $lead->creator ? [
                'id' => $lead->creator->id,
                'name' => $lead->creator->name,
                'image_path' => $lead->creator->image_path
                    ? Storage::disk('public')->url($lead->creator->image_path)
                    : null,
            ] : null,
            'assigned_to' => $lead->assignee ? [
                'id' => $lead->assignee->id,
                'name' => $lead->assignee->name,
                'image_path' => $lead->assignee->image_path
                    ? Storage::disk('public')->url($lead->assignee->image_path)
                    : null,
            ] : null,
            'created_at' => $lead->created_at,
            'updated_at' => $lead->updated_at,
        ];
    }

    private function normalizePhones(Request $request): array
    {
        $phones = $request->has('phones')
            ? collect($request->input('phones', []))
            : collect([[
                'country_code' => $request->input('country_code'),
                'phone' => $request->input('phone'),
                'is_primary' => true,
            ]]);

        $phones = $phones
            ->filter(fn ($phone) => ! empty($phone['phone']))
            ->map(fn ($phone) => [
                'country_code' => $phone['country_code'] ?? null,
                'phone' => trim($phone['phone']),
                'is_primary' => filter_var($phone['is_primary'] ?? false, FILTER_VALIDATE_BOOLEAN),
            ])
            ->unique('phone')
            ->values();

        if ($phones->isEmpty()) {
            throw ValidationException::withMessages([
                'phones' => 'At least one phone is required.',
            ]);
        }

        if ($phones->where('is_primary', true)->count() === 0) {
            $phones[0]['is_primary'] = true;
        }

        if ($phones->where('is_primary', true)->count() > 1) {
            throw ValidationException::withMessages([
                'phones' => 'Only one primary phone is allowed.',
            ]);
        }

        return $phones->all();
    }

    private function normalizeEmails(Request $request): array
    {
        $emails = $request->has('emails')
            ? collect($request->input('emails', []))
            : collect($request->filled('email') ? [[
                'email' => $request->input('email'),
                'is_primary' => true,
            ]] : []);

        $emails = $emails
            ->filter(fn ($email) => ! empty($email['email']))
            ->map(fn ($email) => [
                'email' => strtolower(trim($email['email'])),
                'is_primary' => filter_var($email['is_primary'] ?? false, FILTER_VALIDATE_BOOLEAN),
            ])
            ->unique('email')
            ->values();

        if ($emails->where('is_primary', true)->count() === 0 && $emails->isNotEmpty()) {
            $emails[0]['is_primary'] = true;
        }

        if ($emails->where('is_primary', true)->count() > 1) {
            throw ValidationException::withMessages([
                'emails' => 'Only one primary email is allowed.',
            ]);
        }

        return $emails->all();
    }

    private function duplicateLeadByPhone(array $phones, ?int $exceptLeadId = null): ?Lead
    {
        $numbers = collect($phones)->pluck('phone')->all();

        $query = LeadPhone::whereIn('phone', $numbers);

        if ($exceptLeadId) {
            $query->where('lead_id', '!=', $exceptLeadId);
        }

        $contact = $query->first();

        return $contact ? Lead::with($this->leadRelations())->find($contact->lead_id) : null;
    }

    private function duplicateLeadByEmail(array $emails, ?int $exceptLeadId = null): ?Lead
    {
        $addresses = collect($emails)->pluck('email')->all();

        if (empty($addresses)) {
            return null;
        }

        $query = LeadEmail::whereIn('email', $addresses);

        if ($exceptLeadId) {
            $query->where('lead_id', '!=', $exceptLeadId);
        }

        $contact = $query->first();

        return $contact ? Lead::with($this->leadRelations())->find($contact->lead_id) : null;
    }

    private function syncLeadContacts(Lead $lead, array $phones, array $emails): void
    {
        $lead->phones()->delete();
        $lead->emails()->delete();

        foreach ($phones as $phone) {
            $lead->phones()->create($phone);
        }

        foreach ($emails as $email) {
            $lead->emails()->create($email);
        }

        $primaryPhone = collect($phones)->firstWhere('is_primary', true);
        $primaryEmail = collect($emails)->firstWhere('is_primary', true);

        $lead->forceFill([
            'country_code' => $primaryPhone['country_code'] ?? null,
            'phone' => $primaryPhone['phone'] ?? null,
            'email' => $primaryEmail['email'] ?? null,
        ])->save();
    }

    public function create_lead(Request $request)
    {
        $actor = $request->user();

        $hasCreate = $actor->can('lead_management.raw_lead.create');
        $hasOverride = $actor->can('lead_management.raw_lead.override');

        if (! $hasCreate && ! $hasOverride) {
            return $this->error('Forbidden', 403);
        }
        $request->validate([
            'company_id' => ['required', 'exists:companies,id'],
            'name' => ['required', 'string', 'max:255'],
            'emails' => ['nullable', 'array'],
            'emails.*.email' => ['required_with:emails', 'email', 'max:255'],
            'emails.*.is_primary' => ['nullable', 'integer', 'in:0,1'],
            'phones' => ['nullable', 'array', 'min:1'],
            'phones.*.country_code' => ['nullable', 'string', 'max:10'],
            'phones.*.phone' => ['required_with:phones', 'string', 'max:255'],
            'phones.*.is_primary' => ['nullable', 'integer', 'in:0,1'],
            'assigned_to' => ['nullable', 'exists:users,id'],
        ]);

        $phones = $this->normalizePhones($request);
        $emails = $this->normalizeEmails($request);
        $duplicateLead = $this->duplicateLeadByPhone($phones);

        if ($duplicateLead) {
            return $this->error('Duplicate phone number found.', 409, ['duplicate_lead' => $this->formatLead($duplicateLead)]);
        }

        $duplicateLead = $this->duplicateLeadByEmail($emails);

        if ($duplicateLead) {
            return $this->error('Duplicate email found.', 409, ['duplicate_lead' => $this->formatLead($duplicateLead)]);
        }

        $hasExistingLeads = Lead::where('company_id', $request->company_id)->exists();
        $isPrimary = $hasExistingLeads ? 0 : 1;

        $lead = DB::transaction(function () use ($request, $actor, $isPrimary, $phones, $emails) {
            $lead = Lead::create([
                'company_id' => $request->company_id,
                'name' => $request->name,
                'email' => collect($emails)->firstWhere('is_primary', 1)['email'] ?? null,
                'country_code' => collect($phones)->firstWhere('is_primary', 1)['country_code'] ?? null,
                'phone' => collect($phones)->firstWhere('is_primary', 1)['phone'] ?? null,
                'is_primary' => $isPrimary,
                'created_by' => $actor->id,
                'assigned_to' => $request->assigned_to,
                'created_at' => now()->toDateTimeString(),
            ]);

            $this->syncLeadContacts($lead, $phones, $emails);

            return $lead->fresh($this->leadRelations());
        });

        activity('lead_management')
            ->performedOn($lead)
            ->causedBy($actor)
            ->withProperties([
                'company_id' => $request->company_id,
                'ip' => $request->ip(),
            ])
            ->log("Lead '{$lead->name}' was created by {$actor->name}.");

        return $this->success('Lead created successfully.', $this->formatLead($lead));
    }

    public function update_lead(Request $request)
    {
        $lead = Lead::find($request->id);
        $actor = $request->user();

        if (! $lead) {
            return $this->error('Lead not found.', 404);
        }
        $hasCreate = $actor->can('lead_management.raw_lead.update');
        $hasOverride = $actor->can('lead_management.raw_lead.override');

        if (! $hasCreate && ! $hasOverride) {
            return $this->error('Forbidden', 403);
        }

        $request->validate([
            'id' => ['required', 'integer'],
            'company_id' => ['required', 'exists:companies,id'],
            'name' => ['required', 'string', 'max:255'],
            'emails' => ['nullable', 'array'],
            'emails.*.email' => ['required_with:emails', 'email', 'max:255'],
            'emails.*.is_primary' => ['nullable', 'integer', 'in:0,1'],
            'phones' => ['nullable', 'array', 'min:1'],
            'phones.*.country_code' => ['nullable', 'string', 'max:10'],
            'phones.*.phone' => ['required_with:phones', 'string', 'max:255'],
            'phones.*.is_primary' => ['nullable', 'integer', 'in:0,1'],
            'assigned_to' => ['nullable', 'exists:users,id'],
        ]);

        $phones = $this->normalizePhones($request);
        $emails = $this->normalizeEmails($request);
        $duplicateLead = $this->duplicateLeadByPhone($phones, $lead->id);

        if ($duplicateLead) {
            return $this->error('Duplicate phone number found.', 409, ['duplicate_lead' => $this->formatLead($duplicateLead)]);
        }

        $duplicateLead = $this->duplicateLeadByEmail($emails, $lead->id);

        if ($duplicateLead) {
            return $this->error('Duplicate email found.', 409, ['duplicate_lead' => $this->formatLead($duplicateLead)]);
        }

        $actor = $request->user();

        // Capture old data for the activity log before updating
        $oldData = $lead->only(['name', 'email', 'phone', 'assigned_to']);

        DB::transaction(function () use ($request, $lead, $phones, $emails) {
            $lead->update([
                'company_id' => $request->company_id,
                'name' => $request->name,
                'email' => collect($emails)->firstWhere('is_primary', 1)['email'] ?? null,
                'country_code' => collect($phones)->firstWhere('is_primary', 1)['country_code'] ?? null,
                'phone' => collect($phones)->firstWhere('is_primary', 1)['phone'] ?? null,
                'assigned_to' => $request->assigned_to,
                'updated_at' => now()->toDateTimeString(),
            ]);

            $this->syncLeadContacts($lead, $phones, $emails);
        });

        $lead = $lead->fresh($this->leadRelations());

        if ($oldData != $lead->only(['name', 'email', 'phone', 'assigned_to'])) {
            activity('lead_management')
                ->performedOn($lead)
                ->causedBy($actor)
                ->withProperties([
                    'old' => $oldData,
                    'new' => $lead->only(['name', 'email', 'phone', 'assigned_to']),
                    'ip' => $request->ip(),
                ])
                ->log("Lead '{$lead->name}' was updated by {$actor->name}.");
        }

        return $this->success('Lead updated successfully.', $this->formatLead($lead));
    }

    public function lead_delete(Request $request)
    {
        $actor = $request->user();

        $hasDelete = $actor->can('lead_management.raw_lead.delete');
        $hasOverride = $actor->can('lead_management.raw_lead.override');

        if (! $hasDelete && ! $hasOverride) {
            return $this->error('Forbidden', 403);
        }
        $request->validate([
            'lead_id' => ['required', 'exists:leads,id'],
        ]);

        $lead = Lead::find($request->lead_id);

        if (! $lead) {
            return $this->error('Lead not found');
        }

        // Update is_deleted status
        $lead->is_deleted = 1;
        $lead->deleted_at = now()->toDateTimeString();
        $lead->save();

        return $this->success('Lead deleted successfully');
    }

    public function create_lead_note(Request $request)
    {
        $request->validate([
            'lead_id' => ['required', 'integer', 'exists:leads,id'],
            'note' => ['required', 'string'],
        ]);

        // 1. Fetch the Lead to get its name and company_id for the activity log
        $lead = Lead::find($request->lead_id);
        $actor = $request->user();

        // 2. Create the Lead Note
        $note = LeadNote::create([
            'lead_id' => $request->lead_id,
            'created_by' => $actor->id,
            'note' => $request->note,
            'created_at' => now()->toDateTimeString(),
        ]);

        activity('lead_management')
            ->performedOn($lead)
            ->causedBy($actor)
            ->withProperties([
                'note_id' => $note->id,
                'lead_id' => $lead->lead_id,
                'company_id' => $lead->company_id,
                'ip' => $request->ip(),
            ])
            ->log("A new note was added to Lead '{$lead->name}' by {$actor->name}.");

        // Load creator relationship for the newly created note
        $note->load(['creator' => function ($query) {
            $query->select('id', 'name', 'image_path');
        }]);

        // Format the response with proper image_path handling
        $formattedNote = [
            'id' => $note->id,
            'lead_id' => (int) $note->lead_id,
            'created_by' => $note->creator ? [
                'id' => $note->creator->id,
                'name' => $note->creator->name,
                'image_path' => $note->creator->image_path
                    ? Storage::disk('public')->url($note->creator->image_path)
                    : null,
            ] : null,
            'note' => $note->note,
            'created_at' => $note->created_at,
            'updated_at' => $note->updated_at,
        ];

        return $this->success('Note created successfully.', $formattedNote);
    }

    public function fetch_lead_notes(Request $request)
    {
        $request->validate([
            'lead_id' => ['required', 'exists:leads,id'],
        ]);

        $notes = LeadNote::with(['creator' => function ($query) {
            $query->select('id', 'name', 'image_path');
        }])->where('lead_id', $request->lead_id)
            ->orderBy('created_at', 'desc')->get();

        // Format the response with proper image_path handling
        $formattedNotes = $notes->map(function ($note) {
            return [
                'id' => $note->id,
                'lead_id' => $note->lead_id,
                'created_by' => $note->creator ? [
                    'id' => $note->creator->id,
                    'name' => $note->creator->name,
                    'image_path' => $note->creator->image_path
                        ? Storage::disk('public')->url($note->creator->image_path)
                        : null,
                ] : null,
                'note' => $note->note,
                'created_at' => $note->created_at,
                'updated_at' => $note->updated_at,
            ];
        });

        return $this->success('Lead notes retrieved successfully.', $formattedNotes);
    }

    public function create_lead_follow_up(Request $request)
    {
        $request->validate([
            'lead_id' => ['required', 'exists:leads,id'],
            'remarks' => ['required', 'string'],
            'follow_up_date' => ['required', 'date'],
        ]);

        $lead = Lead::find($request->lead_id);
        $actor = $request->user();

        $followup = LeadFollowup::create([
            'lead_id' => $request->lead_id,
            'created_by' => $actor->id,
            'remarks' => $request->remarks,
            'follow_up_date' => $request->follow_up_date,
            'created_at' => now()->toDateTimeString(),
        ]);

        activity('lead_management')
            ->performedOn($lead)
            ->causedBy($actor)
            ->withProperties([
                'follow_up_id' => $followup->id,
                'lead_id' => $lead->lead_id,
                'company_id' => $lead->company_id,
                'ip' => $request->ip(),
            ])
            ->log("A new follow-up was added to Lead '{$lead->name}' by {$actor->name}.");

        // Load creator relationship
        $followup->load(['creator' => function ($query) {
            $query->select('id', 'name', 'image_path');
        }]);

        // Format the response with proper image_path handling
        $formattedFollowup = [
            'id' => $followup->id,
            'lead_id' => (int) $followup->lead_id,
            'created_by' => $followup->creator ? [
                'id' => $followup->creator->id,
                'name' => $followup->creator->name,
                'image_path' => $followup->creator->image_path
                    ? Storage::disk('public')->url($followup->creator->image_path)
                    : null,
            ] : null,
            'remarks' => $followup->remarks,
            'follow_up_date' => $followup->follow_up_date,
            'created_at' => $followup->created_at,
            'updated_at' => $followup->updated_at,
        ];

        return $this->success('Follow-up created successfully.', $formattedFollowup);
    }

    public function fetch_lead_follow_ups(Request $request)
    {
        $request->validate([
            'lead_id' => ['required', 'exists:leads,id'],
        ]);

        $followups = LeadFollowup::with(['creator' => function ($query) {
            $query->select('id', 'name', 'image_path');
        }])->where('lead_id', $request->lead_id)
            ->orderBy('created_at', 'desc')->get();

        // Format the response with proper image_path handling
        $formattedFollowups = $followups->map(function ($followup) {
            return [
                'id' => $followup->id,
                'lead_id' => $followup->lead_id,
                'created_by' => $followup->creator ? [
                    'id' => $followup->creator->id,
                    'name' => $followup->creator->name,
                    'image_path' => $followup->creator->image_path
                        ? Storage::disk('public')->url($followup->creator->image_path)
                        : null,
                ] : null,
                'remarks' => $followup->remarks,
                'follow_up_date' => $followup->follow_up_date,
                'created_at' => $followup->created_at,
                'updated_at' => $followup->updated_at,
            ];
        });

        return $this->success('Lead follow-ups retrieved successfully.', $formattedFollowups);
    }

    public function convert_to_verified(Request $request)
    {
        $user = $request->user();

        $request->validate([
            'lead_id' => ['required', 'exists:leads,id'],
            'services' => ['required', 'array'],
            'services.*' => ['required', 'exists:products,id'],
        ]);

        $lead = Lead::find($request->lead_id);

        if (! $lead) {
            return $this->error('Lead not found.', 404);
        }

        // Authorization logic
        $isOwner = $lead->created_by === $user->id;
        $isAssignee = $lead->assigned_to === $user->id;

        // Using the specific string from your PermissionSeeder hierarchy
        $hasOverride = $user->can('lead_management.raw_lead.override');

        if (! $isOwner && ! $isAssignee && ! $hasOverride) {
            return $this->error('You are not authorized to convert this lead to verified.', 403);
        }

        $oldStatus = $lead->status;
        $now = now();

        $lead->update([
            'status' => 'verified',
            'cnvt_to_verified_at' => $now,
            'updated_at' => $now,
        ]);

        foreach ($request->services as $service) {
            LeadService::create([
                'lead_id' => $lead->id,
                'product_id' => $service,
                'created_at' => $now,
            ]);
        }

        // Fixed the activity log to use existing variables
        activity('lead_management')
            ->performedOn($lead)
            ->causedBy($user)
            ->withProperties([
                'old_status' => $oldStatus,
                'new_status' => 'verified',
                'authorized_via' => $hasOverride && ! $isOwner && ! $isAssignee ? 'override_permission' : 'direct_assignment',
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent(),
            ])
            ->log("Lead '{$lead->name}' was converted to verified by {$user->name}.");

        return $this->success('Lead converted to verified successfully.', $lead);
    }

    public function convert_to_not_interest(Request $request)
    {
        $user = $request->user();

        $request->validate([
            'lead_id' => ['required', 'exists:leads,id'],
            'interest_remark' => ['required', 'string'],
        ]);

        $lead = Lead::find($request->lead_id);

        if (! $lead) {
            return $this->error('Lead not found.', 404);
        }

        // Authorization logic
        $isOwner = $lead->created_by === $user->id;
        $isAssignee = $lead->assigned_to === $user->id;

        // Using the specific string from your PermissionSeeder hierarchy
        $hasOverride = $user->can('lead_management.raw_lead.override');

        if (! $isOwner && ! $isAssignee && ! $hasOverride) {
            return $this->error('You are not authorized to mark this lead to not interested.', 403);
        }

        $now = now();

        $lead->update([
            'is_interest' => 0,
            'interest_remark' => $request->interest_remark,
            'updated_at' => $now,
        ]);

        activity('lead_management')
            ->performedOn($lead)
            ->causedBy($user)
            ->withProperties([
                'authorized_via' => $hasOverride && ! $isOwner && ! $isAssignee ? 'override_permission' : 'direct_assignment',
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent(),
            ])
            ->log("Lead '{$lead->name}' was converted to not interested by {$user->name}.");

        return $this->success('Lead converted to not interested successfully.', $lead);

    }

    public function convert_to_call_back(Request $request)
    {
        $user = $request->user();

        $request->validate([
            'lead_id' => ['required', 'exists:leads,id'],
            'date_time' => ['required', 'date', 'date_format:Y-m-d H:i:s'],
            'remark' => ['nullable', 'string'],
        ]);

        $lead = Lead::find($request->lead_id);

        if (! $lead) {
            return $this->error('Lead not found.', 404);
        }

        // Authorization logic
        $isOwner = $lead->created_by === $user->id;
        $isAssignee = $lead->assigned_to === $user->id;

        // Using the specific string from your PermissionSeeder hierarchy
        $hasOverride = $user->can('lead_management.raw_lead.override');

        if (! $isOwner && ! $isAssignee && ! $hasOverride) {
            return $this->error('You are not authorized to mark this lead to not interested.', 403);
        }

        $now = now();

        $lead->update([
            'is_call_back' => 1,
            'updated_at' => $now,
        ]);

        LeadCallback::create([
            'lead_id' => $lead->id,
            'created_by' => $user->id,
            'date_time' => $request->date_time,
            'remark' => $request->remark,
        ]);

        activity('lead_management')
            ->performedOn($lead)
            ->causedBy($user)
            ->withProperties([
                'authorized_via' => $hasOverride && ! $isOwner && ! $isAssignee ? 'override_permission' : 'direct_assignment',
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent(),
            ])
            ->log("Lead '{$lead->name}' was converted to call back by {$user->name}.");

        return $this->success('Lead converted to call back successfully.', $lead);

    }

    public function create_lead_sale(Request $request)
    {
        $user = $request->user();

        $hasOverride = $user->can('lead_management.verified_lead.override');

        $request->validate([
            'lead_id' => ['required', 'exists:leads,id'],
            'product_id' => ['required', 'exists:products,id'],
            'price' => ['required', 'numeric'],
            'quantity' => ['required', 'numeric'],
            'total' => ['required', 'numeric'],
            'payment_type' => ['required', 'integer', 'exists:payment_types,id'],
            'remarks' => ['nullable', 'string'],
        ]);

        $lead = Lead::findOrFail($request->lead_id);

        // Permission Check: Only the lead owner or an admin can record a sale
        if ($lead->created_by !== $user->id && ! $hasOverride) {
            return $this->error('Forbidden', 403);
        }

        try {
            \DB::beginTransaction();

            $sale = LeadSale::create([
                'lead_id' => $request->lead_id,
                'product_id' => $request->product_id,
                'price' => $request->price,
                'quantity' => $request->quantity,
                'total' => $request->total,
                'payment_type_id' => $request->payment_type,
                'remarks' => $request->remarks,
                'created_by' => $lead->created_by,
                'assigned_to' => $lead->assigned_to,
                'sale_by' => $user->id,
                'sale_date' => now(),
            ]);

            $lead->update([
                'status' => 'client',
                'cnvt_to_client_at' => now(),
                'updated_at' => now(),
            ]);

            // 1. Log Activity for the SALE record
            activity('sale_management')
                ->performedOn($sale)
                ->causedBy($user)
                ->withProperties([
                    'total_amount' => $request->total,
                    'product_id' => $request->product_id,
                    'ip' => $request->ip(),
                    'user_agent' => $request->userAgent(),
                ])
                ->log("Sale of {$request->total} recorded by {$user->name}.");

            // 2. Log Activity for the LEAD record (Conversion tracking)
            activity('lead_management')
                ->performedOn($lead)
                ->causedBy($user)
                ->withProperties([
                    'sale_id' => $sale->id,
                    'amount' => $request->total,
                    'type' => 'conversion',
                    'ip' => $request->ip(),
                    'user_agent' => $request->userAgent(),
                ])
                ->log("Lead '{$lead->name}' converted to sale.");

            \DB::commit();

            return $this->success('Lead sale created successfully.');

        } catch (\Throwable $th) {
            \DB::rollBack();

            return $this->error($th->getMessage(), 500);
        }
    }

    public function fetch_all_leads(Request $request)
    {
        $user = $request->user();

        $hasRead = $user->can('lead_management.raw_lead.read');
        $hasOverride = $user->can('lead_management.raw_lead.override');

        $paginatedLeads = Lead::with($this->leadRelations());

        // If user has override permission, show all data
        if ($hasOverride) {
            // No filtering needed - show all verified leads
        } // If user only has read permission, show own and subordinate data
        elseif ($hasRead) {
            $accessibleUserIds = $this->accessibleUserIdsFor($user);

            $paginatedLeads->where(function ($query) use ($accessibleUserIds) {
                $query->whereIn('created_by', $accessibleUserIds)
                    ->orWhereIn('assigned_to', $accessibleUserIds);
            });
        } // If user has neither permission, deny access
        else {
            return $this->error('Forbidden', 403);
        }

        $paginatedLeads = $paginatedLeads->latest()->paginate(15);

        $leads = $paginatedLeads->getCollection()->map(fn ($lead) => $this->formatLead($lead));

        return $this->success('Leads fetched successfully.', [
            'data' => $leads,
            'current_page' => $paginatedLeads->currentPage(),
            'next_page' => $paginatedLeads->hasMorePages()
                ? $paginatedLeads->currentPage() + 1
                : null,
            'last_page' => $paginatedLeads->lastPage(),
            'total_items' => $paginatedLeads->total(),
            'per_page' => $paginatedLeads->perPage(),
        ]);

    }

    public function export_leads(Request $request)
    {
        $user = $request->user();

        $hasRead = $user->can('lead_management.raw_lead.read');
        $hasOverride = $user->can('lead_management.raw_lead.override');

        if (! $hasRead && ! $hasOverride) {
            return $this->error('Forbidden', 403);
        }

        $validated = $request->validate([
            'format' => ['nullable', 'string', 'in:excel,pdf'],
            'search' => ['nullable', 'string', 'max:255'],
            'status' => ['nullable', 'string', 'in:raw,verified,client'],
            'company_id' => ['nullable', 'integer', 'exists:companies,id'],
            'source' => ['nullable', 'string', 'max:255'],
            'priority' => ['nullable', 'string', 'in:low,high'],
            'created_by' => ['nullable', 'integer', 'exists:users,id'],
            'assigned_to' => ['nullable', 'integer', 'exists:users,id'],
            'is_interest' => ['nullable', 'boolean'],
            'is_call_back' => ['nullable', 'boolean'],
            'is_primary' => ['nullable', 'boolean'],
            'created_from' => ['nullable', 'date'],
            'created_to' => ['nullable', 'date'],
            'updated_from' => ['nullable', 'date'],
            'updated_to' => ['nullable', 'date'],
            'verified_from' => ['nullable', 'date'],
            'verified_to' => ['nullable', 'date'],
            'client_from' => ['nullable', 'date'],
            'client_to' => ['nullable', 'date'],
        ]);

        $format = $validated['format'] ?? 'pdf';
        $filters = $validated;
        unset($filters['format']);

        $leadsQuery = Lead::with($this->leadRelations())->where('is_deleted', false);

        if (! $hasOverride) {
            $accessibleUserIds = $this->accessibleUserIdsFor($user);

            $leadsQuery->where(function ($query) use ($accessibleUserIds) {
                $query->whereIn('created_by', $accessibleUserIds)
                    ->orWhereIn('assigned_to', $accessibleUserIds);
            });
        }

        $this->applyLeadExportFilters($leadsQuery, $filters);

        $leads = $leadsQuery->latest()->get();

        $account = Account::first();

        if ($format === 'excel') {
            $fileName = 'leads_'.date('Y_m_d_His').'.xlsx';

            activity('lead_management')
                ->causedBy($user)
                ->withProperties([
                    'format' => 'excel',
                    'filters' => $filters,
                    'count' => $leads->count(),
                    'ip' => $request->ip(),
                ])
                ->log("Leads exported to Excel by {$user->name}");

            return Excel::download(new LeadsExport($leads), $fileName, null, [
                'Content-Disposition' => 'attachment; filename="'.$fileName.'"',
                'X-Filename' => $fileName,
                'Access-Control-Expose-Headers' => 'Content-Disposition, X-Filename',
            ]);
        }

        $options = new Options;
        $options->set('defaultFont', 'Arial');
        $dompdf = new Dompdf($options);

        $html = view('exports.leads_pdf', compact('leads', 'filters', 'account'))->render();

        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'landscape');
        $dompdf->render();

        $fileName = 'leads_'.date('Y_m_d_His').'.pdf';
        $pdf = $dompdf->output();

        activity('lead_management')
            ->causedBy($user)
            ->withProperties([
                'format' => 'pdf',
                'filters' => $filters,
                'count' => $leads->count(),
                'ip' => $request->ip(),
            ])
            ->log("Leads exported to PDF by {$user->name}");

        return response($pdf, 200, [
            'Content-Type' => 'application/pdf',
            'Content-Disposition' => 'attachment; filename="'.$fileName.'"',
            'Content-Length' => strlen($pdf),
            'X-Filename' => $fileName,
            'Access-Control-Expose-Headers' => 'Content-Disposition, X-Filename',
        ]);
    }

    private function applyLeadExportFilters($query, array $filters): void
    {
        if (! empty($filters['search'])) {
            $search = $filters['search'];

            $query->where(function ($query) use ($search) {
                $query->where('name', 'LIKE', "%{$search}%")
                    ->orWhere('email', 'LIKE', "%{$search}%")
                    ->orWhere('phone', 'LIKE', "%{$search}%")
                    ->orWhereHas('emails', function ($query) use ($search) {
                        $query->where('email', 'LIKE', "%{$search}%");
                    })
                    ->orWhereHas('phones', function ($query) use ($search) {
                        $query->where('phone', 'LIKE', "%{$search}%");
                    })
                    ->orWhereHas('company', function ($query) use ($search) {
                        $query->where('name', 'LIKE', "%{$search}%");
                    });
            });
        }

        foreach (['status', 'company_id', 'source', 'priority', 'created_by', 'assigned_to', 'is_interest', 'is_call_back', 'is_primary'] as $field) {
            if (array_key_exists($field, $filters) && $filters[$field] !== null && $filters[$field] !== '') {
                $query->where($field, $filters[$field]);
            }
        }

        $dateRanges = [
            'created' => 'created_at',
            'updated' => 'updated_at',
            'verified' => 'cnvt_to_verified_at',
            'client' => 'cnvt_to_client_at',
        ];

        foreach ($dateRanges as $filterPrefix => $column) {
            if (! empty($filters[$filterPrefix.'_from'])) {
                $query->whereDate($column, '>=', $filters[$filterPrefix.'_from']);
            }

            if (! empty($filters[$filterPrefix.'_to'])) {
                $query->whereDate($column, '<=', $filters[$filterPrefix.'_to']);
            }
        }
    }

    public function fetch_all_raw_leads(Request $request)
    {
        $user = $request->user();

        $hasRead = $user->can('lead_management.raw_lead.read');
        $hasOverride = $user->can('lead_management.raw_lead.override');

        $paginatedLeads = Lead::with($this->leadRelations())->where('status', 'raw');

        // If user has override permission, show all data
        if ($hasOverride) {
            // No filtering needed - show all raw leads
        } // If user only has read permission, show own and subordinate data
        elseif ($hasRead) {
            $accessibleUserIds = $this->accessibleUserIdsFor($user);

            $paginatedLeads->where(function ($query) use ($accessibleUserIds) {
                $query->whereIn('created_by', $accessibleUserIds)
                    ->orWhereIn('assigned_to', $accessibleUserIds);
            });
        } // If user has neither permission, deny access
        else {
            return $this->error('Forbidden', 403);
        }

        $paginatedLeads = $paginatedLeads->latest()->paginate(15);

        $leads = $paginatedLeads->getCollection()->map(fn ($lead) => $this->formatLead($lead));

        return $this->success('Raw leads fetched successfully.', [
            'data' => $leads,
            'current_page' => $paginatedLeads->currentPage(),
            'next_page' => $paginatedLeads->hasMorePages()
                ? $paginatedLeads->currentPage() + 1
                : null,
            'last_page' => $paginatedLeads->lastPage(),
            'total_items' => $paginatedLeads->total(),
            'per_page' => $paginatedLeads->perPage(),
        ]);
    }

    public function fetch_verified_leads(Request $request)
    {
        $user = $request->user();

        $hasRead = $user->can('lead_management.verified_lead.read');
        $hasOverride = $user->can('lead_management.verified_lead.override');

        $paginatedLeads = Lead::with($this->leadRelations())->where('status', 'verified');

        // If user has override permission, show all data
        if ($hasOverride) {
            // No filtering needed - show all verified leads
        } // If user only has read permission, show own and subordinate data
        elseif ($hasRead) {
            $accessibleUserIds = $this->accessibleUserIdsFor($user);

            $paginatedLeads->where(function ($query) use ($accessibleUserIds) {
                $query->whereIn('created_by', $accessibleUserIds)
                    ->orWhereIn('assigned_to', $accessibleUserIds);
            });
        } // If user has neither permission, deny access
        else {
            return $this->error('Forbidden', 403);
        }

        $paginatedLeads = $paginatedLeads->latest()->paginate(15);

        $leads = $paginatedLeads->getCollection()->map(fn ($lead) => $this->formatLead($lead));

        return $this->success('Leads fetched successfully.', [
            'data' => $leads,
            'current_page' => $paginatedLeads->currentPage(),
            'next_page' => $paginatedLeads->hasMorePages()
                ? $paginatedLeads->currentPage() + 1
                : null,
            'last_page' => $paginatedLeads->lastPage(),
            'total_items' => $paginatedLeads->total(),
            'per_page' => $paginatedLeads->perPage(),
        ]);

    }

    public function fetch_all_clients(Request $request)
    {
        $user = $request->user();

        $hasRead = $user->can('lead_management.client.read');
        $hasOverride = $user->can('lead_management.client.override');

        $paginatedLeads = Lead::with($this->leadRelations())->where('status', 'client');

        // If user has override permission, show all data
        if ($hasOverride) {
            // No filtering needed - show all client leads
        } // If user only has read permission, show own and subordinate data
        elseif ($hasRead) {
            $accessibleUserIds = $this->accessibleUserIdsFor($user);

            $paginatedLeads->where(function ($query) use ($accessibleUserIds) {
                $query->whereIn('created_by', $accessibleUserIds)
                    ->orWhereIn('assigned_to', $accessibleUserIds);
            });
        } // If user has neither permission, deny access
        else {
            return $this->error('Forbidden', 403);
        }

        $paginatedLeads = $paginatedLeads->latest()->paginate(15);

        $leads = $paginatedLeads->getCollection()->map(fn ($lead) => $this->formatLead($lead));

        return $this->success('Leads fetched successfully.', [
            'data' => $leads,
            'current_page' => $paginatedLeads->currentPage(),
            'next_page' => $paginatedLeads->hasMorePages()
                ? $paginatedLeads->currentPage() + 1
                : null,
            'last_page' => $paginatedLeads->lastPage(),
            'total_items' => $paginatedLeads->total(),
            'per_page' => $paginatedLeads->perPage(),
        ]);

    }

    public function search_all_leads(Request $request)
    {
        $user = $request->user();

        $request->validate([
            'search' => ['required', 'string', 'min:3', 'max:255'],
        ]);

        $search = $request->search;

        $hasAnyPermission =
            $user->can('lead_management.raw_lead.read') ||
            $user->can('lead_management.raw_lead.override') ||
            $user->can('lead_management.verified_lead.read') ||
            $user->can('lead_management.verified_lead.override') ||
            $user->can('lead_management.client.read') ||
            $user->can('lead_management.client.override');

        if (!$hasAnyPermission) {
            return $this->error('Forbidden', 403);
        }

        $leadsQuery = Lead::with($this->leadRelations())
            ->where(function ($q) use ($search) {
                $q->where('name', 'LIKE', "%{$search}%")
                    ->orWhere('email', 'LIKE', "%{$search}%")
                    ->orWhere('phone', 'LIKE', "%{$search}%")
                    ->orWhereHas('emails', function ($q) use ($search) {
                        $q->where('email', 'LIKE', "%{$search}%");
                    })
                    ->orWhereHas('phones', function ($q) use ($search) {
                        $q->where('phone', 'LIKE', "%{$search}%");
                    })
                    ->orWhereHas('company', function ($q) use ($search) {
                        $q->where('name', 'LIKE', "%{$search}%");
                    });
            });

        $leadsQuery->where(function ($query) use ($user) {

            $applyReadFilter = function ($q) use ($user) {
                $q->where(function ($sub) use ($user) {
                    $sub->where('created_by', $user->id)
                        ->orWhere('assigned_to', $user->id)
                        ->orWhereIn('created_by', function ($sq) use ($user) {
                            $sq->select('child_user_id')
                                ->from('user_mappings')
                                ->where('parent_user_id', $user->id);
                        })
                        ->orWhereIn('assigned_to', function ($sq) use ($user) {
                            $sq->select('child_user_id')
                                ->from('user_mappings')
                                ->where('parent_user_id', $user->id);
                        });
                });
            };

            /*
            |--------------------------------------------------------------------------
            | RAW LEADS
            |--------------------------------------------------------------------------
            */
            if ($user->can('lead_management.raw_lead.override')) {

                $query->orWhere('status', 'raw');

            } elseif ($user->can('lead_management.raw_lead.read')) {

                $query->orWhere(function ($q) use ($applyReadFilter) {
                    $q->where('status', 'raw');

                    $applyReadFilter($q);
                });
            }

            /*
            |--------------------------------------------------------------------------
            | VERIFIED LEADS
            |--------------------------------------------------------------------------
            */
            if ($user->can('lead_management.verified_lead.override')) {

                $query->orWhere('status', 'verified');

            } elseif ($user->can('lead_management.verified_lead.read')) {

                $query->orWhere(function ($q) use ($applyReadFilter) {
                    $q->where('status', 'verified');

                    $applyReadFilter($q);
                });
            }

            /*
            |--------------------------------------------------------------------------
            | CLIENT LEADS
            |--------------------------------------------------------------------------
            */
            if ($user->can('lead_management.client.override')) {

                $query->orWhere('status', 'client');

            } elseif ($user->can('lead_management.client.read')) {

                $query->orWhere(function ($q) use ($applyReadFilter) {
                    $q->where('status', 'client');

                    $applyReadFilter($q);
                });
            }
        });

        $leads = $leadsQuery->latest()->get();

        $leads = $leads->map(fn ($lead) => $this->formatLead($lead));

        return $this->success('Leads search result.', $leads);
    }

    public function lead_single_transfer(Request $request)
    {
        $request->validate([
            'id' => ['required', 'exists:users,id'],
            'lead_id' => ['required', 'exists:leads,id'],
        ]);

        $user = User::find($request->id);
        $lead = Lead::find($request->lead_id);

        if (! $lead) {
            return $this->error('Lead does not exist.', 404);
        }

        $new_creator = $user->id;
        $old_creator = $lead->created_by;

        if ($request->lead_status === 'raw') {
            if (! $user->can('lead_management.raw_lead.update') &&
                ! $user->can('lead_management.raw_lead.override') &&
                $old_creator !== $new_creator) {
                return $this->error('Forbidden', 403);
            }
        }
        if ($request->lead_status === 'verified') {
            if (! $user->can('lead_management.verified_lead.update') &&
                ! $user->can('lead_management.verified_lead.override') &&
                $old_creator !== $new_creator) {
                return $this->error('Forbidden', 403);
            }
        }
        if ($request->lead_status === 'client') {
            if (! $user->can('lead_management.client_lead.update') &&
                ! $user->can('lead_management.client_lead.override') &&
                $old_creator !== $new_creator) {
                return $this->error('Forbidden', 403);
            }
        }

        $lead->created_by = $new_creator;

        if (! $lead->save()) {
            return $this->error('Failed to transfer lead.', 500);
        }

        return $this->success('Lead transferred successfully.', $this->formatLead($lead));

    }

    public function lead_single_share(Request $request)
    {
        $creator = $request->user();
        $request->validate([
            'id' => ['required', 'exists:users,id'],
            'lead_id' => ['required', 'exists:leads,id'],
        ]);

        $user = User::find($request->id);
        $lead = Lead::find($request->lead_id);

        if (! $lead) {
            return $this->error('Lead does not exist.', 404);
        }
        $new_creator = $creator->id;
        $old_creator = $lead->created_by;
        $new_assignee = $user->id;
        $old_assignee = $lead->assigned_to;

        if ($request->lead_status === 'raw') {
            if (! $user->can('lead_management.raw_lead.update') &&
                ! $user->can('lead_management.raw_lead.override') &&
                ($old_assignee !== $new_assignee && $old_creator !== $new_creator)) {
                return $this->error('Forbidden', 403);
            }
        }
        if ($request->lead_status === 'verified') {
            if (! $user->can('lead_management.verified_lead.update') &&
                ! $user->can('lead_management.verified_lead.override') &&
                ($old_assignee !== $new_assignee && $old_creator !== $new_creator)) {
                return $this->error('Forbidden', 403);
            }
        }
        if ($request->lead_status === 'client') {
            if (! $user->can('lead_management.client_lead.update') &&
                ! $user->can('lead_management.client_lead.override') &&
                ($old_assignee !== $new_assignee && $old_creator !== $new_creator)) {
                return $this->error('Forbidden', 403);
            }
        }

        $lead->assigned_to = $new_assignee;

        if (! $lead->save()) {
            return $this->error('Failed to share lead.', 500);
        }

        return $this->success('Lead shared successfully.', $this->formatLead($lead));

    }

    public function lead_priority_update(Request $request)
    {
        $user = $request->user();

        $request->validate([
            'lead_id' => ['required', 'exists:leads,id'],
            'priority' => ['required', 'string', 'in:low,high'],
        ]);

        $lead = Lead::findOrFail($request->lead_id);

        $hasOverride = $user->can('lead_management.raw_lead.override');

        if ($user->id !== $lead->created_by && ! $hasOverride) {
            return $this->error('Forbidden', 403);
        }

        try {
            $oldPriority = $lead->priority;

            $lead->update([
                'priority' => $request->priority,
                'updated_at' => now(),
            ]);

            activity('lead_management')
                ->performedOn($lead)
                ->causedBy($user)
                ->withProperties([
                    'lead_id' => $request->lead_id,
                    'old_priority' => $oldPriority,
                    'new_priority' => $request->priority,
                    'ip' => $request->ip(),
                ])
                ->log("Lead priority for ID {$lead->id} updated from {$oldPriority} to {$request->priority} by {$user->name}.");

            return $this->success('Lead priority updated successfully.', $this->formatLead($lead));

        } catch (\Throwable $th) {
            return $this->error('Failed to update lead priority: '.$th->getMessage(), 500);
        }
    }

    /**
     * Import leads from Excel/CSV file
     */
    public function import_leads(Request $request)
    {
        $user = $request->user();

        $hasCreate = $user->can('lead_management.raw_lead.create');
        $hasOverride = $user->can('lead_management.raw_lead.override');

        if (!$hasCreate && !$hasOverride) {
            return $this->error('Forbidden', 403);
        }

        $request->validate([
            'file' => ['required', 'file', 'mimes:xlsx,xls,csv', 'max:20480'], // 20MB max
            'assigned_to' => ['nullable', 'exists:users,id'],
        ]);

        try {
            $results = LeadImportService::importFromFile(
                $request->file('file'),
                $user->id,
                $request->assigned_to ?? null
            );

            activity('lead_management')
                ->causedBy($user)
                ->withProperties([
                    'success_count' => $results['success'],
                    'failed_count' => $results['failed'],
                    'errors' => $results['errors'],
                    'ip' => $request->ip(),
                    'user_agent' => $request->userAgent(),
                ])
                ->log("Lead import completed: {$results['success']} successful, {$results['failed']} failed by {$user->name}");

            return $this->success(
                'Lead import completed',
                [
                    'total_imported' => $results['success'],
                    'total_failed' => $results['failed'],
                    'errors' => $results['errors'],
                ]
            );
        } catch (\Exception $e) {
            return $this->error('Failed to import leads: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Download lead import template
     */
    public function download_import_template()
    {
        try {
            return LeadImportService::generateExampleFile();
        } catch (\Exception $e) {
            return $this->error('Failed to generate template: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Set a phone number as primary for a lead
     */
    public function set_primary_phone(Request $request)
    {
        $user = $request->user();

        $request->validate([
            'lead_id' => ['required', 'exists:leads,id'],
            'phone_id' => ['required', 'exists:lead_phones,id'],
        ]);

        try {
            DB::beginTransaction();

            $lead = Lead::findOrFail($request->lead_id);

            // Check permissions based on lead status
            $leadStatus = $lead->status;
            if ($leadStatus === 'raw') {
                $hasUpdate = $user->can('lead_management.raw_lead.update');
                $hasOverride = $user->can('lead_management.raw_lead.override');
            } elseif ($leadStatus === 'verified') {
                $hasUpdate = $user->can('lead_management.verified_lead.update');
                $hasOverride = $user->can('lead_management.verified_lead.override');
            } elseif ($leadStatus === 'client') {
                $hasUpdate = $user->can('lead_management.client_lead.update');
                $hasOverride = $user->can('lead_management.client_lead.override');
            } else {
                return $this->error('Invalid lead status.', 400);
            }

            if (!$hasUpdate && !$hasOverride) {
                return $this->error('Forbidden', 403);
            }

            $phone = LeadPhone::where('id', $request->phone_id)
                ->where('lead_id', $request->lead_id)
                ->first();

            if (!$phone) {
                DB::rollBack();
                return $this->error('Phone not found for this lead.', 404);
            }

            // Set all phones for this lead to non-primary
            LeadPhone::where('lead_id', $request->lead_id)
                ->update(['is_primary' => false]);

            // Set the selected phone as primary
            $phone->update(['is_primary' => true]);

            // Update the lead's main phone fields
            $lead->update([
                'country_code' => $phone->country_code,
                'phone' => $phone->phone,
            ]);

            DB::commit();

            activity('lead_management')
                ->performedOn($lead)
                ->causedBy($user)
                ->withProperties([
                    'phone_id' => $phone->id,
                    'phone' => $phone->phone,
                    'ip' => $request->ip(),
                    'user_agent' => $request->userAgent(),
                ])
                ->log("Primary phone set to '{$phone->phone}' for lead '{$lead->name}' by {$user->name}.");

            return $this->success('Primary phone set successfully.', $this->formatLead($lead));

        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->error('Failed to set primary phone: ' . $th->getMessage(), 500);
        }
    }

    /**
     * Set an email as primary for a lead
     */
    public function set_primary_email(Request $request)
    {
        $user = $request->user();

        $request->validate([
            'lead_id' => ['required', 'exists:leads,id'],
            'email_id' => ['required', 'exists:lead_emails,id'],
        ]);

        try {
            DB::beginTransaction();

            $lead = Lead::findOrFail($request->lead_id);

            // Check permissions based on lead status
            $leadStatus = $lead->status;
            if ($leadStatus === 'raw') {
                $hasUpdate = $user->can('lead_management.raw_lead.update');
                $hasOverride = $user->can('lead_management.raw_lead.override');
            } elseif ($leadStatus === 'verified') {
                $hasUpdate = $user->can('lead_management.verified_lead.update');
                $hasOverride = $user->can('lead_management.verified_lead.override');
            } elseif ($leadStatus === 'client') {
                $hasUpdate = $user->can('lead_management.client_lead.update');
                $hasOverride = $user->can('lead_management.client_lead.override');
            } else {
                return $this->error('Invalid lead status.', 400);
            }

            if (!$hasUpdate && !$hasOverride) {
                return $this->error('Forbidden', 403);
            }

            $email = LeadEmail::where('id', $request->email_id)
                ->where('lead_id', $request->lead_id)
                ->first();

            if (!$email) {
                DB::rollBack();
                return $this->error('Email not found for this lead.', 404);
            }

            // Set all emails for this lead to non-primary
            LeadEmail::where('lead_id', $request->lead_id)
                ->update(['is_primary' => false]);

            // Set the selected email as primary
            $email->update(['is_primary' => true]);

            // Update the lead's main email field
            $lead->update([
                'email' => $email->email,
            ]);

            DB::commit();

            activity('lead_management')
                ->performedOn($lead)
                ->causedBy($user)
                ->withProperties([
                    'email_id' => $email->id,
                    'email' => $email->email,
                    'ip' => $request->ip(),
                    'user_agent' => $request->userAgent(),
                ])
                ->log("Primary email set to '{$email->email}' for lead '{$lead->name}' by {$user->name}.");

            return $this->success('Primary email set successfully.', $this->formatLead($lead));

        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->error('Failed to set primary email: ' . $th->getMessage(), 500);
        }
    }
}
