<?php

namespace App\Service\Admin;

use App\Models\Vendor;
use Illuminate\Support\Str;

class VendorService
{

    public function updateVendor(Vendor $vendor, array $data): Vendor
    {
        try {
            // Handle pricing_file upload if present
            if (isset($data['pricing_file'])) {
                $pricingPath = $data['pricing_file']->store('uploads/pricing', 'public');
                $vendor->pricing_file = $pricingPath;
            }

            // Handle cac_document upload if present
            if (isset($data['cac_document'])) {
                $cacPath = $data['cac_document']->store('uploads/cac', 'public');
                $vendor->cac_document = $cacPath;
            }

            // Update other fields
            $vendor->update([
                'business_name'     => $data['business_name'] ?? $vendor->business_name,
                'contact_name'      => $data['contact_name'] ?? $vendor->contact_name,
                'email'             => $data['email'] ?? $vendor->email,
                'phone'             => $data['phone'] ?? $vendor->phone,
                'business_address'  => $data['business_address'] ?? $vendor->business_address,
                'website'           => $data['website'] ?? $vendor->website,
                'vendor_type'       => $data['vendor_type'] ?? $vendor->vendor_type,
                'print_services'    => $data['print_services'] ?? $vendor->print_services,
                'materials_sold'    => $data['materials_sold'] ?? $vendor->materials_sold,
                'machine_types'     => $data['machine_types'] ?? $vendor->machine_types,
                'turnaround_time'   => $data['turnaround_time'] ?? $vendor->turnaround_time,
                'minimum_order_qty' => $data['minimum_order_qty'] ?? $vendor->minimum_order_qty,
                'additional_notes'  => $data['additional_notes'] ?? $vendor->additional_notes,
                'status'            => $data['status'] ?? $vendor->status,
            ]);

            return $vendor;
        } catch (\Exception $e) {
            \Log::error('Vendor update failed: ' . $e->getMessage());
            throw $e; // Let the controller handle the error response
        }
    }



    public function deleteVendor(string $trackId): bool
    {
        $vendor = Vendor::where('track_id', $trackId)->first();

        if (!$vendor) {
            return false;
        }

        return $vendor->delete();
    }
}
