<?php

namespace App\Services\MasterData;

use App\Services\BaseService;
use App\Repositories\CustomerVendorRepository;
use App\Models\CustomerVendor;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class CustomerVendorService extends BaseService
{
    protected CustomerVendorRepository $customerVendorRepository;

    public function __construct(CustomerVendorRepository $repository)
    {
        parent::__construct($repository);
        $this->customerVendorRepository = $repository;
    }

    /**
     * Get all customers
     */
    public function getCustomers(): Collection
    {
        return $this->customerVendorRepository->getCustomers();
    }

    /**
     * Get all vendors
     */
    public function getVendors(): Collection
    {
        return $this->customerVendorRepository->getVendors();
    }

    /**
     * Get active customers/vendors
     */
    public function getActive(): Collection
    {
        return $this->customerVendorRepository->getActive();
    }

    /**
     * Search
     */
    public function search(string $term): Collection
    {
        return $this->customerVendorRepository->search($term);
    }

    /**
     * Get all with contacts
     */
    public function getAllWithContacts(): Collection
    {
        return $this->customerVendorRepository->getWithContacts();
    }

    /**
     * Get single customer/vendor with contacts by ID
     */
    public function getWithContacts(int $id): ?CustomerVendor
    {
        return CustomerVendor::with('contactPersons')->find($id);
    }

    /**
     * Create with contact persons
     */
    public function createWithContacts(array $data, array $contacts = []): CustomerVendor
    {
        return DB::transaction(function () use ($data, $contacts) {
            $customerVendor = $this->create($data);

            // Filter out empty contacts (where name, email, and mobile are all empty)
            $validContacts = array_filter($contacts, function ($contact) {
                return !empty(trim($contact['name'] ?? '')) ||
                       !empty(trim($contact['email'] ?? '')) ||
                       !empty(trim($contact['mobile'] ?? ''));
            });

            foreach ($validContacts as $contact) {
                $contact['customer_vendor_id'] = $customerVendor->id;
                $customerVendor->contactPersons()->create($contact);
            }

            $this->logAction('Customer/Vendor created', ['id' => $customerVendor->id]);
            return $customerVendor->fresh(['contactPersons']);
        });
    }

    /**
     * Update with contact persons
     */
    public function updateWithContacts(int $id, array $data, array $contacts = []): CustomerVendor
    {
        return DB::transaction(function () use ($id, $data, $contacts) {
            $customerVendor = $this->update($id, $data);

            // Filter out empty contacts
            $validContacts = array_filter($contacts, function ($contact) {
                return !empty(trim($contact['name'] ?? '')) ||
                       !empty(trim($contact['email'] ?? '')) ||
                       !empty(trim($contact['mobile'] ?? ''));
            });

            // Remove old contacts and add new ones
            $customerVendor->contactPersons()->delete();
            foreach ($validContacts as $contact) {
                $contact['customer_vendor_id'] = $id;
                $customerVendor->contactPersons()->create($contact);
            }

            $this->logAction('Customer/Vendor updated', ['id' => $id]);
            return $customerVendor->fresh(['contactPersons']);
        });
    }
}
