<?php

namespace App\Http\Controllers;

use App\Models\Quotation;
use App\Models\QuotationDetail;
use App\Models\QuotationDraft;
use App\Models\QuotationEmail;
use App\Models\QuotationProductDetail;
use App\Models\AccountDocument;
use App\Services\QuotationPdfService;
use App\Services\QuotationEmailService;
use App\Services\QuotationAttachmentService;
use App\Traits\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Throwable;

class QuotationController extends Controller
{
    use ApiResponse;

    private function quotation_format(quotation $data)
    {
        $data->load('lead:id,name,email,country_code,phone',
            'lead.company:id,name,website,address,zipcode',
            'creator:id,name,email,country_code,phone,image_path',
            'details.product',
            'details.product_details');

            return [
                'id' => $data->id,
                'quotation_number' => $data->quotation_number,
                'lead' => $data->lead ? [
                    'id' => $data->lead->id,
                    'name' => $data->lead->name,
                    'email' => $data->lead->email,
                    'country_code' => $data->lead->country_code,
                    'phone' => $data->lead->phone,
                ] : null,
                'company' => $data->lead?->company ? [
                    'id' => $data->lead->company->id,
                    'name' => $data->lead->company->name,
                    'website' => $data->lead->company->website,
                    'address' => $data->lead->company->address,
                    'zipcode' => $data->lead->company->zipcode,
                ] : null,
                'email_subject' => $data->email_subject,
                'email_body' => $data->email_body,
                'created_at' => $data->created_at,
                'updated_at' => $data->updated_at,
                'creator' => $data->creator ? [
                    'id' => $data->creator->id,
                    'name' => $data->creator->name,
                    'email' => $data->creator->email,
                    'country_code' => $data->creator->country_code,
                    'phone' => $data->creator->phone,
                    'image_path' => $data->creator->image_path ? Storage::disk('public')->url($data->creator->image_path) : null,
                ] : null,
                'details' => $data->details ? $data->details->map(function ($detail) {
                    return [
                        'id' => $detail->id,
                        'product' => $detail->product ? [
                            'id' => $detail->product->id,
                            'name' => $detail->product->name,
                        ] : null,
                        'product_details' => $detail->product_details ? $detail->product_details->map(function ($pDetail) {
                            return [
                                'id' => $pDetail->id,
                                'description' => $pDetail->description,
                                'price' => (float)$pDetail->price,
                                'quantity' => (float)$pDetail->quantity,
                                'unit' => $pDetail->unit,
                                'total' => (float)$pDetail->total,
                            ];
                        }) : [],
                    ];
                }) : [],
            ];
    }

    private function quotation_draft_format(QuotationDraft $data): array
    {
        $data->load(
            'lead:id,name,email,country_code,phone',
            'lead.company:id,name,website,address,zipcode',
            'creator:id,name,email,country_code,phone,image_path',
        );

        return [
            'id' => $data->id,
            'lead' => $data->lead ? [
                'id' => $data->lead->id,
                'name' => $data->lead->name,
                'email' => $data->lead->email,
                'country_code' => $data->lead->country_code,
                'phone' => $data->lead->phone,
            ] : null,
            'company' => $data->lead?->company ? [
                'id' => $data->lead->company->id,
                'name' => $data->lead->company->name,
                'website' => $data->lead->company->website,
                'address' => $data->lead->company->address,
                'zipcode' => $data->lead->company->zipcode,
            ] : null,
            'email_subject' => $data->email_subject,
            'email_body' => $data->email_body,
            'products' => $data->products ?? [],
            'created_at' => $data->created_at,
            'updated_at' => $data->updated_at,
            'creator' => $data->creator ? [
                'id' => $data->creator->id,
                'name' => $data->creator->name,
                'email' => $data->creator->email,
                'country_code' => $data->creator->country_code,
                'phone' => $data->creator->phone,
                'image_path' => $data->creator->image_path ? Storage::disk('public')->url($data->creator->image_path) : null,
            ] : null,
        ];
    }

    private function draftValidationRules(bool $requireDraftId = false): array
    {
        return [
            'draft_id' => [$requireDraftId ? 'required' : 'nullable', 'exists:quotation_drafts,id'],
            'lead_id' => ['nullable', 'exists:leads,id'],
            'email_subject' => ['nullable', 'string'],
            'email_body' => ['nullable', 'string'],
            'products' => ['nullable', 'array'],
            'products.*.product_id' => ['nullable', 'exists:products,id'],
            'products.*.details' => ['nullable', 'array'],
            'products.*.details.*.description' => ['nullable', 'string'],
            'products.*.details.*.price' => ['nullable', 'numeric', 'min:0'],
            'products.*.details.*.quantity' => ['nullable', 'numeric', 'min:0'],
            'products.*.details.*.unit' => ['nullable', 'string'],
            'products.*.details.*.total' => ['nullable', 'numeric', 'min:0'],
        ];
    }

    private function finalQuotationValidationRules(): array
    {
        return [
            'lead_id' => ['required', 'exists:leads,id'],
            'email_subject' => ['required', 'string'],
            'email_body' => ['required', 'string'],
            'products' => ['required', 'array', 'min:1'],
            'products.*.product_id' => ['required', 'exists:products,id'],
            'products.*.details' => ['required', 'array', 'min:1'],
            'products.*.details.*.description' => ['required', 'string'],
            'products.*.details.*.price' => ['required', 'numeric', 'min:0'],
            'products.*.details.*.quantity' => ['required', 'numeric', 'min:0'],
            'products.*.details.*.unit' => ['nullable', 'string'],
            'products.*.details.*.total' => ['required', 'numeric', 'min:0'],
        ];
    }

    private function storeQuotation(array $validated, int $userId): Quotation
    {
        $quotation = Quotation::create([
            'lead_id' => $validated['lead_id'],
            'created_by' => $userId,
            'email_subject' => $validated['email_subject'],
            'email_body' => $validated['email_body'],
        ]);

        foreach ($validated['products'] as $product) {
            $quotationDetail = QuotationDetail::create([
                'quotation_id' => $quotation->id,
                'product_id' => $product['product_id'],
            ]);

            foreach ($product['details'] as $detail) {
                QuotationProductDetail::create([
                    'quotation_detail_id' => $quotationDetail->id,
                    'description' => $detail['description'],
                    'price' => $detail['price'],
                    'quantity' => $detail['quantity'],
                    'unit' => $detail['unit'] ?? null,
                    'total' => $detail['total'],
                ]);
            }
        }

        return $quotation;
    }

    /**
     * @throws Throwable
     */
    public function create_quotation(Request $request)
    {
        $user = $request->user();

        $hasCreate = $user->can('quotation_management.quotation.create');
        $hasOverride = $user->can('quotation_management.quotation.override');

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

        $validated = $request->validate($this->finalQuotationValidationRules());

        $quotation = DB::transaction(function () use ($validated, $user) {
            return $this->storeQuotation($validated, $user->id);
        });

        $formatted_data = $this->quotation_format($quotation);

        activity('quotation_management')
            ->performedOn($quotation)
            ->causedBy($user)
            ->withProperties([
                'quotation_number' => $quotation->quotation_number,
                'lead_id' => $quotation->lead_id,
                'email_subject' => $quotation->email_subject,
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent(),
            ])
            ->log("Quotation {$quotation->quotation_number} created by {$user->name}.");

        return $this->success(
            'Quotation created successfully',
            $formatted_data,
            201
        );
    }

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

        $hasCreate = $user->can('quotation_management.quotation.create');
        $hasOverride = $user->can('quotation_management.quotation.override');

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

        $validated = $request->validate($this->draftValidationRules());

        $draft = QuotationDraft::create([
            'lead_id' => $validated['lead_id'] ?? null,
            'created_by' => $user->id,
            'email_subject' => $validated['email_subject'] ?? null,
            'email_body' => $validated['email_body'] ?? null,
            'products' => $validated['products'] ?? [],
        ]);

        activity('quotation_management')
            ->performedOn($draft)
            ->causedBy($user)
            ->withProperties([
                'draft_id' => $draft->id,
                'lead_id' => $draft->lead_id,
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent(),
            ])
            ->log("Quotation draft {$draft->id} created by {$user->name}.");

        return $this->success(
            'Quotation draft created successfully',
            $this->quotation_draft_format($draft),
            201
        );
    }

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

        $hasUpdate = $user->can('quotation_management.quotation.update');
        $hasOverride = $user->can('quotation_management.quotation.override');

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

        $validated = $request->validate($this->draftValidationRules(requireDraftId: true));
        $draft = QuotationDraft::find($validated['draft_id']);

        if (!$draft) {
            return $this->error('Quotation draft not found', 404);
        }

        $updateData = [];
        foreach (['lead_id', 'email_subject', 'email_body', 'products'] as $field) {
            if ($request->has($field)) {
                $updateData[$field] = $validated[$field] ?? null;
            }
        }

        if (!empty($updateData)) {
            $draft->update($updateData);
        }

        activity('quotation_management')
            ->performedOn($draft)
            ->causedBy($user)
            ->withProperties([
                'draft_id' => $draft->id,
                'lead_id' => $draft->lead_id,
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent(),
            ])
            ->log("Quotation draft {$draft->id} updated by {$user->name}.");

        return $this->success(
            'Quotation draft updated successfully',
            $this->quotation_draft_format($draft),
            200
        );
    }

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

        $hasRead = $user->can('quotation_management.quotation.read');
        $hasOverride = $user->can('quotation_management.quotation.override');

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

        $validated = $request->validate([
            'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
            'search' => ['nullable', 'string'],
            'lead_id' => ['nullable', 'exists:leads,id'],
            'sort_by' => ['nullable', 'in:created_at,updated_at'],
            'sort_order' => ['nullable', 'in:asc,desc'],
        ]);

        $perPage = $validated['per_page'] ?? 15;
        $sortBy = $validated['sort_by'] ?? 'updated_at';
        $sortOrder = $validated['sort_order'] ?? 'desc';

        $query = QuotationDraft::with(['creator', 'lead']);

        if (!empty($validated['search'])) {
            $search = $validated['search'];
            $query->where(function ($q) use ($search) {
                $q->where('email_subject', 'like', "%{$search}%")
                    ->orWhere('email_body', 'like', "%{$search}%");
            });
        }

        if (!empty($validated['lead_id'])) {
            $query->where('lead_id', $validated['lead_id']);
        }

        $paginatedDrafts = $query->orderBy($sortBy, $sortOrder)->paginate($perPage);
        $formattedData = $paginatedDrafts->getCollection()->map(function ($draft) {
            return $this->quotation_draft_format($draft);
        });

        return $this->success(
            'Quotation drafts fetched successfully',
            [
                'data' => $formattedData,
                'current_page' => $paginatedDrafts->currentPage(),
                'next_page' => $paginatedDrafts->hasMorePages()
                    ? $paginatedDrafts->currentPage() + 1
                    : null,
                'last_page' => $paginatedDrafts->lastPage(),
                'total_items' => $paginatedDrafts->total(),
                'per_page' => $paginatedDrafts->perPage(),
            ],
            200
        );
    }

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

        $hasRead = $user->can('quotation_management.quotation.read');
        $hasOverride = $user->can('quotation_management.quotation.override');

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

        $validated = $request->validate([
            'draft_id' => ['required', 'exists:quotation_drafts,id'],
        ]);

        $draft = QuotationDraft::find($validated['draft_id']);

        if (!$draft) {
            return $this->error('Quotation draft not found', 404);
        }

        return $this->success(
            'Quotation draft fetched successfully',
            $this->quotation_draft_format($draft),
            200
        );
    }

    /**
     * @throws Throwable
     */
    public function finalize_quotation_draft(Request $request)
    {
        $user = $request->user();

        $hasCreate = $user->can('quotation_management.quotation.create');
        $hasOverride = $user->can('quotation_management.quotation.override');

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

        $validated = $request->validate([
            'draft_id' => ['required', 'exists:quotation_drafts,id'],
        ]);

        $draft = QuotationDraft::find($validated['draft_id']);

        if (!$draft) {
            return $this->error('Quotation draft not found', 404);
        }

        $payload = [
            'lead_id' => $draft->lead_id,
            'email_subject' => $draft->email_subject,
            'email_body' => $draft->email_body,
            'products' => $draft->products ?? [],
        ];

        $quotationData = Validator::make($payload, $this->finalQuotationValidationRules())->validate();

        $quotation = DB::transaction(function () use ($quotationData, $draft, $user) {
            $quotation = $this->storeQuotation($quotationData, $user->id);

            $draft->update([
                'is_deleted' => 1,
                'deleted_at' => now(),
            ]);

            return $quotation;
        });

        activity('quotation_management')
            ->performedOn($quotation)
            ->causedBy($user)
            ->withProperties([
                'draft_id' => $draft->id,
                'quotation_number' => $quotation->quotation_number,
                'lead_id' => $quotation->lead_id,
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent(),
            ])
            ->log("Quotation draft {$draft->id} finalized as {$quotation->quotation_number} by {$user->name}.");

        return $this->success(
            'Quotation draft finalized successfully',
            $this->quotation_format($quotation),
            201
        );
    }

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

        $hasDelete = $user->can('quotation_management.quotation.delete');
        $hasOverride = $user->can('quotation_management.quotation.override');

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

        $validated = $request->validate([
            'draft_id' => ['required', 'exists:quotation_drafts,id'],
        ]);

        $draft = QuotationDraft::find($validated['draft_id']);

        if (!$draft) {
            return $this->error('Quotation draft not found', 404);
        }

        $draft->update([
            'is_deleted' => 1,
            'deleted_at' => now(),
        ]);

        activity('quotation_management')
            ->performedOn($draft)
            ->causedBy($user)
            ->withProperties([
                'draft_id' => $draft->id,
                'lead_id' => $draft->lead_id,
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent(),
            ])
            ->log("Quotation draft {$draft->id} deleted by {$user->name}.");

        return $this->success(
            'Quotation draft deleted successfully',
            ['draft_id' => $validated['draft_id']],
            200
        );
    }

    /**
     * @throws Throwable
     */
    public function update_quotation(Request $request)
    {
        $user = $request->user();

        $hasUpdate = $user->can('quotation_management.quotation.update');
        $hasOverride = $user->can('quotation_management.quotation.override');

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

        $validated = $request->validate([
            'quotation_id' => ['required', 'exists:quotations,id'],
            'lead_id' => ['nullable', 'exists:leads,id'],
            'email_subject' => ['nullable', 'string'],
            'email_body' => ['nullable', 'string'],
            'products' => ['nullable', 'array'],
            'products.*.product_id' => ['required_with:products', 'exists:products,id'],
            'products.*.details' => ['required_with:products', 'array'],
            'products.*.details.*.description' => ['required_with:products', 'string'],
            'products.*.details.*.price' => ['required_with:products', 'numeric', 'min:0'],
            'products.*.details.*.quantity' => ['required_with:products', 'numeric', 'min:0'],
            'products.*.details.*.unit' => ['nullable', 'string'],
            'products.*.details.*.total' => ['required_with:products', 'numeric', 'min:0'],
        ]);

        $quotation = Quotation::find($validated['quotation_id']);

        if (!$quotation) {
            return $this->error('Quotation not found', 404);
        }

        $oldData = $quotation->only(['lead_id', 'email_subject', 'email_body']);

        $quotation = DB::transaction(function () use ($validated, $quotation) {
            $updateData = array_filter([
                'lead_id' => $validated['lead_id'] ?? null,
                'email_subject' => $validated['email_subject'] ?? null,
                'email_body' => $validated['email_body'] ?? null,
            ], fn($value) => $value !== null);

            if (!empty($updateData)) {
                $quotation->update($updateData);
            }

            if (isset($validated['products'])) {
                $quotation->details?->each(function ($detail) {
                    $detail->product_details()->delete();
                });
                $quotation->details?->each->delete();

                foreach ($validated['products'] as $product) {
                    $quotationDetail = QuotationDetail::create([
                        'quotation_id' => $quotation->id,
                        'product_id' => $product['product_id'],
                    ]);

                    foreach ($product['details'] as $detail) {
                        QuotationProductDetail::create([
                            'quotation_detail_id' => $quotationDetail->id,
                            'description' => $detail['description'],
                            'price' => $detail['price'],
                            'quantity' => $detail['quantity'],
                            'unit' => $detail['unit'] ?? null,
                            'total' => $detail['total'],
                        ]);
                    }
                }
            }

            return $quotation;
        });

        $formatted_data = $this->quotation_format($quotation);

        if ($quotation->wasChanged()) {
            activity('quotation_management')
                ->performedOn($quotation)
                ->causedBy($user)
                ->withProperties([
                    'old' => $oldData,
                    'new' => $quotation->only(['lead_id', 'email_subject', 'email_body']),
                    'quotation_number' => $quotation->quotation_number,
                    'ip' => $request->ip(),
                    'user_agent' => $request->userAgent(),
                ])
                ->log("Quotation {$quotation->quotation_number} updated by {$user->name}.");
        }

        return $this->success(
            'Quotation updated successfully',
            $formatted_data,
            200
        );
    }

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

        $hasDelete = $user->can('quotation_management.quotation.delete');
        $hasOverride = $user->can('quotation_management.quotation.override');

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

        $validated = $request->validate([
            'quotation_id' => ['required', 'exists:quotations,id'],
        ]);

        $quotation = Quotation::find($validated['quotation_id']);

        if (!$quotation) {
            return $this->error('Quotation not found', 404);
        }

        $quotation->update([
            'is_deleted' => 1,
            'deleted_at' => now()
        ]);

        activity('quotation_management')
            ->performedOn($quotation)
            ->causedBy($user)
            ->withProperties([
                'quotation_number' => $quotation->quotation_number,
                'lead_id' => $quotation->lead_id,
                'email_subject' => $quotation->email_subject,
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent(),
            ])
            ->log("Quotation {$quotation->quotation_number} deleted by {$user->name}.");

        return $this->success(
            'Quotation deleted successfully',
            ['quotation_id' => $validated['quotation_id']],
            200
        );
    }

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

        $hasRead = $user->can('quotation_management.quotation.read');
        $hasOverride = $user->can('quotation_management.quotation.override');

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

        $validated = $request->validate([
            'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
            'search' => ['nullable', 'string'],
            'lead_id' => ['nullable', 'exists:leads,id'],
            'sort_by' => ['nullable', 'in:created_at,quotation_number'],
            'sort_order' => ['nullable', 'in:asc,desc'],
        ]);

        $perPage = $validated['per_page'] ?? 15;
        $sortBy = $validated['sort_by'] ?? 'created_at';
        $sortOrder = $validated['sort_order'] ?? 'desc';

        $query = Quotation::with(['details.product_details', 'details.product', 'creator', 'lead']);

        if (!empty($validated['search'])) {
            $search = $validated['search'];
            $query->where(function ($q) use ($search) {
                $q->where('quotation_number', 'like', "%{$search}%")
                    ->orWhere('email_subject', 'like', "%{$search}%");
            });
        }

        if (!empty($validated['lead_id'])) {
            $query->where('lead_id', $validated['lead_id']);
        }

        $paginatedQuotations = $query->orderBy($sortBy, $sortOrder)->paginate($perPage);

        $formatted_data = $paginatedQuotations->getCollection()->map(function ($quotation) {
            return $this->quotation_format($quotation);
        });

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

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

        $hasRead = $user->can('quotation_management.quotation.read');
        $hasOverride = $user->can('quotation_management.quotation.override');

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

        $validated = $request->validate([
            'id' => ['required', 'exists:quotations,id'],
        ]);

        $quotation = Quotation::find($validated['id']);

        if (!$quotation) {
            return $this->error('Quotation not found', 404);
        }

        $formatted_data = $this->quotation_format($quotation);

        return $this->success(
            'Quotation fetched successfully',
            $formatted_data,
            200
        );
    }

    /**
     * Send quotation to email
     */
    public function send_quotation_to_email(Request $request)
    {
        $user = $request->user();

        $hasRead = $user->can('quotation_management.quotation.read');
        $hasOverride = $user->can('quotation_management.quotation.override');

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

        try {
            $validated = $request->validate([
                'quotation_id' => ['required', 'exists:quotations,id'],
                'recipient_emails' => ['required', 'array', 'min:1'],
                'recipient_emails.*' => ['email'],
                'documents' => ['nullable', 'array', 'max:5'],
                'documents.*' => ['exists:account_documents,id'],
                'additional_attachments' => ['nullable', 'array', 'max:5'],
                'additional_attachments.*' => ['file'],
                'subject_override' => ['nullable', 'string'],
                'body_override' => ['nullable', 'string'],
            ]);

            $quotation = Quotation::find($validated['quotation_id']);

            if (!$quotation) {
                return $this->error('Quotation not found', 404);
            }

            // Initialize services
            $pdfService = new QuotationPdfService();
            $attachmentService = new QuotationAttachmentService();
            $emailService = new QuotationEmailService($pdfService);

            // Handle additional attachments
            $attachmentPaths = [];
            if (!empty($validated['additional_attachments'])) {
                $attachmentPaths = $attachmentService->storeAttachments(
                    $validated['additional_attachments']
                );
            }

            // Handle account documents
            if (!empty($validated['documents'])) {
                $documents = AccountDocument::whereIn('id', $validated['documents'])->get();
                foreach ($documents as $document) {
                    if ($document->file_path) {
                        $attachmentPaths[] = Storage::disk('public')->url($document->file_path);
                    }
                }
            }

            // Send email
            $quotationEmail = $emailService->sendQuotation(
                $quotation,
                $validated['recipient_emails'],
                $user,
                $attachmentPaths,
                $validated['subject_override'] ?? null,
                $validated['body_override'] ?? null
            );

            // Log activity
            activity('quotation_management')
                ->performedOn($quotation)
                ->causedBy($user)
                ->withProperties([
                    'quotation_number' => $quotation->quotation_number,
                    'recipient_emails' => $validated['recipient_emails'],
                    'status' => $quotationEmail->status,
                    'ip' => $request->ip(),
                    'user_agent' => $request->userAgent(),
                ])
                ->log("Quotation {$quotation->quotation_number} email sent to " . implode(', ', $validated['recipient_emails']));

            $response = [
                'id' => $quotationEmail->id,
                'quotation_id' => $quotationEmail->quotation_id,
                'recipient_emails' => $quotationEmail->recipient_emails,
                'subject' => $quotationEmail->subject,
                'status' => $quotationEmail->status,
                'sent_at' => $quotationEmail->sent_at,
                'error_message' => $quotationEmail->error_message,
            ];

            return $this->success(
                'Quotation email sent successfully',
                $response,
                200
            );
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 400);
        }
    }

    /**
     * Get email sending history for quotation
     */
    public function get_quotation_email_history(Request $request)
    {
        $user = $request->user();

        $hasRead = $user->can('quotation_management.quotation.read');
        $hasOverride = $user->can('quotation_management.quotation.override');

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

        $validated = $request->validate([
            'quotation_id' => ['required', 'exists:quotations,id'],
        ]);

        $quotation = Quotation::find($validated['quotation_id']);

        if (!$quotation) {
            return $this->error('Quotation not found', 404);
        }

        $pdfService = new QuotationPdfService();
        $emailService = new QuotationEmailService($pdfService);

        $history = $emailService->getEmailHistory($quotation);

        return $this->success('Email history fetched successfully',$history,200);
    }

    /**
     * Resend quotation email
     */
    public function resend_quotation_email(Request $request)
    {
        $user = $request->user();

        $hasRead = $user->can('quotation_management.quotation.read');
        $hasOverride = $user->can('quotation_management.quotation.override');

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

        try {
            $validated = $request->validate([
                'quotation_email_id' => ['required', 'exists:quotation_emails,id'],
            ]);

            $quotationEmail = QuotationEmail::find($validated['quotation_email_id']);

            if (!$quotationEmail) {
                return $this->error('Quotation email record not found', 404);
            }

            // Initialize services
            $pdfService = new QuotationPdfService();
            $emailService = new QuotationEmailService($pdfService);

            // Resend email
            $quotationEmail = $emailService->resendQuotation($quotationEmail, $user);

            // Log activity
            activity('quotation_management')
                ->performedOn($quotationEmail->quotation)
                ->causedBy($user)
                ->withProperties([
                    'quotation_number' => $quotationEmail->quotation->quotation_number,
                    'recipient_emails' => $quotationEmail->recipient_emails,
                    'status' => 'resent',
                    'ip' => $request->ip(),
                    'user_agent' => $request->userAgent(),
                ])
                ->log("Quotation {$quotationEmail->quotation->quotation_number} email resent");

            $response = [
                'id' => $quotationEmail->id,
                'quotation_id' => $quotationEmail->quotation_id,
                'recipient_emails' => $quotationEmail->recipient_emails,
                'subject' => $quotationEmail->subject,
                'status' => $quotationEmail->status,
                'sent_at' => $quotationEmail->sent_at,
                'error_message' => $quotationEmail->error_message,
            ];

            return $this->success(
                'Quotation email resent successfully',
                $response,
                200
            );
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 400);
        }
    }

    /**
     * Download quotation as PDF
     */
    public function download_quotation_pdf(Request $request)
    {
        $user = $request->user();

        $request->validate([
            'id' => ['required', 'exists:quotations,id'],
        ]);

        $hasExport = $user->can('quotation_management.quotation.export');
        $hasOverride = $user->can('quotation_management.quotation.override');

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

        try {
            $quotation = Quotation::find($request->id);

            if (!$quotation) {
                return $this->error('Quotation not found', 404);
            }

            $pdfService = new QuotationPdfService();
            return $pdfService->generatePdf($quotation, download: true);
        } catch (\Exception $e) {
            return $this->error('Failed to generate PDF: ' . $e->getMessage(), 400);
        }
    }
}
