<?php
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Reusable contacts UI + API for Inventory/Books/Invoice.
 * Host product must extend INTEGRAZO_WCZO_ZOHO_Base (has ->request()).
 */

if (!trait_exists('INTEGRAZO_WCZO_ZOHO_Contacts_Trait')) {

    trait INTEGRAZO_WCZO_ZOHO_Contacts_Trait
    {

        /**
         * Public wrapper if you want to call it directly elsewhere.
         * Returns contact_id or null.
         */
        public function get_contact_id_by_email(string $organization_id, string $email, bool $retry = true): ?string
        {
            return $this->find_contact_id_by_email($organization_id, $email, $retry);
        }

        /**
         * Find contact strictly by email using Zoho Inventory list-contacts.
         * GET /contacts?organization_id={orgId}&email={email}
         * Returns contact_id or null.
         */
        protected function find_contact_id_by_email(string $organization_id, string $email, bool $retry = true): ?string
        {
            $email = trim($email);
            if ($email === '') {
                return null;
            }

            $res = $this->request('GET', 'contacts', [
                'query' => [
                    'organization_id' => $organization_id,
                    'email'           => $email,
                    'per_page'        => 200,
                ],
                'json'  => false,
            ], $retry);


            if (!isset($res['status'])) {
                return null;
            }

            $contacts = $res['body']['contacts'] ?? null;
            if (!is_array($contacts)) {
                return null;
            }

            foreach ($contacts as $c) {
                // Match top-level email
                $topMatch = !empty($c['email']) && strcasecmp((string)$c['email'], $email) === 0;
                // Or any contact_persons email
                $personMatch = !empty($c['contact_persons']) && array_filter(
                    (array)$c['contact_persons'],
                    fn($p) => !empty($p['email']) && strcasecmp((string)$p['email'], $email) === 0
                );

                if ($topMatch || $personMatch) {
                    return isset($c['contact_id']) ? (string)$c['contact_id'] : null;
                }
            }

            return null;
        }

        /** Existing create/update remain unchanged */
        public function create_contact(string $organization_id, array $data, bool $retry = true): array
        {
            $payload = $this->normalize_contact_payload($data);

            $res = $this->request('POST', 'contacts', [
                'query' => ['organization_id' => $organization_id],
                'json'  => true,
                'body'  => $payload,
            ], $retry);

            if (!isset($res['status'])) {
                return $res;
            }

            return INTEGRAZO_WCZO_Product_Util::create_error_response('SUCCESS', "Contact created successfully.", $res['body']);
        }


        /**
         * Flat → nested + primary contact logic.
         * Copies contact_salutation to top-level and to the primary contact_person.
         */
        protected function normalize_contact_payload(array $data): array
        {
            $payload = $data;

            $billing = array_filter([
                'attention' => $data['billing_address_attention'] ?? null,
                'address'   => $data['billing_address_address']   ?? null,
                'street2'   => $data['billing_address_street2']   ?? null,
                'city'      => $data['billing_address_city']      ?? null,
                'state'     => $data['billing_address_state']     ?? null,
                'zip'       => $data['billing_address_zip']       ?? null,
                'country'   => $data['billing_address_country']   ?? null,
                'fax'       => $data['billing_address_fax']       ?? null,
                'phone'     => $data['billing_address_phone']     ?? null,
            ], fn($v) => $v !== null && $v !== '');
            if ($billing) {
                $payload['billing_address'] = $billing;
            }

            $shipping = array_filter([
                'attention' => $data['shipping_address_attention'] ?? null,
                'address'   => $data['shipping_address_address']   ?? null,
                'street2'   => $data['shipping_address_street2']   ?? null,
                'city'      => $data['shipping_address_city']      ?? null,
                'state'     => $data['shipping_address_state']     ?? null,
                'zip'       => $data['shipping_address_zip']       ?? null,
                'country'   => $data['shipping_address_country']   ?? null,
                'fax'       => $data['shipping_address_fax']       ?? null,
                'phone'     => $data['shipping_address_phone']     ?? null,
            ], fn($v) => $v !== null && $v !== '');
            if ($shipping) {
                $payload['shipping_address'] = $shipping;
            }

            if (!empty($data['contact_salutation']) && empty($payload['contact_salutation'])) {
                $payload['contact_salutation'] = $data['contact_salutation'];
            } elseif (!empty($data['salutation']) && empty($payload['contact_salutation'])) {
                $payload['contact_salutation'] = $data['salutation'];
            }

            $basic_keys = ['first_name', 'last_name', 'email', 'phone', 'mobile'];
            $has_basic  = array_filter($basic_keys, fn($k) => !empty($data[$k]));
            if (empty($payload['contact_persons']) && $has_basic) {
                $person_salutation = $data['salutation'] ?? $data['contact_salutation'] ?? '';
                $payload['contact_persons'] = [[
                    'salutation'         => $person_salutation,
                    'first_name'         => $data['first_name'] ?? '',
                    'last_name'          => $data['last_name']  ?? '',
                    'email'              => $data['email']      ?? '',
                    'phone'              => $data['phone']      ?? '',
                    'mobile'             => $data['mobile']     ?? '',
                    'is_primary_contact' => true,
                ]];
                foreach ($basic_keys as $k) {
                    unset($payload[$k]);
                }
            }

            $flat = [
                'billing_address_attention',
                'billing_address_address',
                'billing_address_street2',
                'billing_address_city',
                'billing_address_state',
                'billing_address_zip',
                'billing_address_country',
                'billing_address_fax',
                'billing_address_phone',
                'shipping_address_attention',
                'shipping_address_address',
                'shipping_address_street2',
                'shipping_address_city',
                'shipping_address_state',
                'shipping_address_zip',
                'shipping_address_country',
                'shipping_address_fax',
                'shipping_address_phone',
            ];
            foreach ($flat as $k) {
                unset($payload[$k]);
            }

            return $payload;
        }
    }
}
