<?php

namespace Kanzu\StoreVoiceAI;

// Prevent direct file access.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

use Kanzu\StoreVoiceAI\Services\Store_Voice_AI_API;

trait Working_Hours_Trait
{
    protected static function week_day_keys()
    {
        return array( 'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun' );
    }

    protected function working_hours_day_label($key)
    {
        $labels = array(
            'mon' => __( 'Mon', 'storevoiceai-for-woocommerce' ),
            'tue' => __( 'Tue', 'storevoiceai-for-woocommerce' ),
            'wed' => __( 'Wed', 'storevoiceai-for-woocommerce' ),
            'thu' => __( 'Thu', 'storevoiceai-for-woocommerce' ),
            'fri' => __( 'Fri', 'storevoiceai-for-woocommerce' ),
            'sat' => __( 'Sat', 'storevoiceai-for-woocommerce' ),
            'sun' => __( 'Sun', 'storevoiceai-for-woocommerce' ),
        );

        return isset($labels[$key]) ? $labels[$key] : $key;
    }

    protected function default_working_hours()
    {
        $out = array();
        foreach (self::week_day_keys() as $key) {
            $out[$key] = array(
                'off'   => in_array($key, array('sat', 'sun'), true),
                'start' => '09:00',
                'end'   => '17:00',
            );
        }

        return $out;
    }

    protected function get_working_hours()
    {
        $stored = get_option(Onboarding::OPT_WORKING_HOURS, array());
        if (!is_array($stored)) {
            $stored = array();
        }

        return $this->sanitize_working_hours($stored);
    }

    protected function sanitize_working_hours($raw)
    {
        $defaults = $this->default_working_hours();
        $clean    = array();

        foreach (self::week_day_keys() as $key) {
            $day  = isset($raw[$key]) && is_array($raw[$key]) ? $raw[$key] : array();
            $base = $defaults[$key];

            $start = $this->sanitize_working_time($day, 'start', $base['start']);
            $end   = $this->sanitize_working_time($day, 'end', $base['end']);

            if (!$this->working_time_range_is_valid($start, $end)) {
                $start = $base['start'];
                $end   = $base['end'];
            }

            $clean[$key] = array(
                'off'   => !empty($day['off']),
                'start' => $start,
                'end'   => $end,
            );
        }

        return $clean;
    }

    protected function to_api_working_hours(array $hours)
    {
        $map = array(
            'mon' => 'monday',
            'tue' => 'tuesday',
            'wed' => 'wednesday',
            'thu' => 'thursday',
            'fri' => 'friday',
            'sat' => 'saturday',
            'sun' => 'sunday',
        );
        $out = array();

        foreach ($map as $short => $long) {
            $day = isset($hours[$short]) ? $hours[$short] : null;
            $out[$long] = is_array($day) && empty($day['off'])
                ? array(
                    'start' => $day['start'],
                    'end'   => $day['end'],
                )
                : null;
        }

        return $out;
    }

    protected function sync_default_availability_profile(array $hours)
    {
        $api      = new Store_Voice_AI_API();
        $profiles = $api->get_availability_profiles();

        if (is_wp_error($profiles)) {
            return;
        }

        $list = $profiles;
        if (is_array($profiles) && isset($profiles['data']) && is_array($profiles['data'])) {
            $list = $profiles['data'];
        }
        if (!is_array($list) || empty($list)) {
            return;
        }

        $default = null;
        foreach ($list as $profile) {
            if (is_array($profile) && !empty($profile['isDefault'])) {
                $default = $profile;
                break;
            }
        }
        if ($default === null) {
            $default = $list[0];
        }

        $profile_id = isset($default['id']) ? (string) $default['id'] : '';
        if ($profile_id === '') {
            return;
        }

        $name = (isset($default['name']) && is_string($default['name']) && $default['name'] !== '')
            ? $default['name']
            : 'Default';

        $api->update_availability_profile($profile_id, array(
            'name'         => $name,
            'workingHours' => $this->to_api_working_hours($hours),
            'isDefault'    => true,
        ));
    }

    private function sanitize_working_time(array $day, string $field, string $fallback): string
    {
        return isset($day[$field]) && is_string($day[$field]) && preg_match('/^(?:[01]\d|2[0-3]):[0-5]\d$/', $day[$field])
            ? $day[$field]
            : $fallback;
    }

    private function working_time_range_is_valid(string $start, string $end): bool
    {
        $start_time = strtotime('1970-01-01 ' . $start);
        $end_time   = strtotime('1970-01-01 ' . $end);

        return $start_time !== false && $end_time !== false && $start_time < $end_time;
    }
}
