<?php

namespace App\Services;

use App\Models\Business;
use App\Models\Lead;

class DuplicateCheckService
{
    public function checkDuplicate($email, $mobile, $excludeId = null, $type = 'both')
    {
        $errors = [];

        // Check in businesses
        if (in_array($type, ['both', 'business'])) {
            $businessEmailExists = Business::where('email', $email)
                ->when($excludeId, fn($q) => $q->where('id', '!=', $excludeId))
                ->exists();

            $businessMobileExists = Business::where('mobile', $mobile)
                ->when($excludeId, fn($q) => $q->where('id', '!=', $excludeId))
                ->exists();

            // Only block if BOTH exist (as per requirement: "In Mobile or Email if one is unique then Team or Head can Add")
            if ($businessEmailExists && $businessMobileExists) {
                $errors['email'] = 'This email already exists in Business records.';
                $errors['mobile'] = 'This mobile number already exists in Business records.';
            }
        }

        // Check in leads
        if (in_array($type, ['both', 'lead'])) {
            $leadEmailExists = Lead::where('email', $email)
                ->when($excludeId, fn($q) => $q->where('id', '!=', $excludeId))
                ->exists();

            $leadMobileExists = Lead::where('mobile', $mobile)
                ->when($excludeId, fn($q) => $q->where('id', '!=', $excludeId))
                ->exists();

            // Only block if BOTH exist
            if ($leadEmailExists && $leadMobileExists) {
                if (!isset($errors['email'])) {
                    $errors['email'] = 'This email already exists in Lead records.';
                }
                if (!isset($errors['mobile'])) {
                    $errors['mobile'] = 'This mobile number already exists in Lead records.';
                }
            }
        }

        return $errors;
    }
}
