<?php

if (!defined('ABSPATH')) {
    exit;
}

class WNC_Connect_Health {

    public static function init() {
        add_action('add_meta_boxes', [__CLASS__, 'add_metabox']);
    }

    public static function add_metabox() {
        $screens = function_exists('wnc_get_enabled_post_types')
            ? wnc_get_enabled_post_types()
            : ['post', 'page'];

        if (empty($screens)) {
            return;
        }

        add_meta_box(
            'wnc_connect_health',
            'Where Next Connect Health',
            [__CLASS__, 'render_metabox'],
            $screens,
            'side',
            'high'
        );
    }

    public static function render_metabox($post) {
        if (!class_exists('WNC_Connect_Tags')) {
            echo '<p>Where Next Connect tags are not loaded.</p>';
            return;
        }

        $data = WNC_Connect_Tags::get_data($post->ID);

        $checks = self::checks($data, $post->ID);
        $score  = self::score($checks);
        $stars  = self::stars($score);

        echo '<div style="font-size:14px;">';

        echo '<p style="font-size:20px;margin:0 0 8px;"><strong>' . esc_html($stars) . ' ' . esc_html($score) . '%</strong></p>';

        echo '<p style="margin:0 0 12px;color:#555;">Compatibility score based on currently available Where Next data.</p>';

        echo '<ul style="margin:0;">';

        foreach ($checks as $check) {
            $icon  = $check['ok'] ? '✅' : '⚠️';
            $color = $check['ok'] ? '#166534' : '#92400e';

            echo '<li style="margin-bottom:7px;color:' . esc_attr($color) . ';">';
            echo esc_html($icon . ' ' . $check['label']);
            echo '</li>';
        }

        echo '</ul>';

        echo '<hr>';

        echo '<p style="margin-bottom:0;color:#555;">Blank fields are allowed, but adding more data improves the import experience in Where Next.</p>';

        echo '</div>';
    }

    public static function checks($data, $post_id = 0) {
        $has_image = self::has_any($data, [
            'coverImageUri',
            'image',
            'cover-image',
        ]);

        $has_price = self::has_any($data, [
            'pricing',
            'price',
            'adultPrice',
            'childPrice',
            'familyPrice',
            'concessionPrice',
            'adult-price',
            'child-price',
            'family-price',
            'concession-price',
        ]);

        $has_opening = self::has_any($data, [
            'openingTimes',
            'opening-times',
            'monday',
            'tuesday',
            'wednesday',
            'thursday',
            'friday',
            'saturday',
            'sunday',
        ]);

        $checks = [
            [
                'label'  => 'Name',
                'ok'     => self::filled($data['name'] ?? ''),
                'weight' => 20,
            ],
            [
                'label'  => 'Website',
                'ok'     => self::filled($data['website'] ?? ''),
                'weight' => 10,
            ],
            [
                'label'  => 'Image',
                'ok'     => $has_image,
                'weight' => 10,
            ],
            [
                'label'  => 'Category',
                'ok'     => self::filled($data['category'] ?? ''),
                'weight' => 10,
            ],
        ];

        $is_event = strtolower(trim((string) ($data['placeMode'] ?? ''))) === 'event';

        if ($post_id && function_exists('wnc_is_event_post_type')) {
            $is_event = wnc_is_event_post_type(get_post_type($post_id));
        }

        if ($is_event) {
            $checks[] = [
                'key' => 'eventStartDate',
                'label' => 'Event Start Date',
                'ok' => self::filled($data['eventStartDate'] ?? ''),
                'weight' => 25,
            ];
            $checks[] = [
                'key' => 'eventEndDate',
                'label' => 'Event End Date',
                'ok' => self::filled($data['eventEndDate'] ?? ''),
                'weight' => 15,
            ];
        } else {
            $has_location = self::filled($data['address'] ?? '')
                || self::filled($data['postcode'] ?? '')
                || self::filled($data['what3words'] ?? '')
                || (
                    self::filled($data['latitude'] ?? '')
                    && self::filled($data['longitude'] ?? '')
                );

            $checks[] = [
                'key' => 'location',
                'label' => 'Address / Location',
                'ok' => $has_location,
                'weight' => 20,
            ];
            $checks[] = [
                'key' => 'openingTimes',
                'label' => 'Opening Times',
                'ok' => $has_opening,
                'weight' => 10,
            ];
            $checks[] = [
                'key' => 'pricing',
                'label' => 'Pricing',
                'ok' => $has_price,
                'weight' => 10,
            ];
        }

        foreach ($checks as $index => $check) {
            if (empty($checks[$index]['key'])) {
                $checks[$index]['key'] = sanitize_key($check['label']);
            }
        }

        return $checks;
    }

    public static function score($checks) {
        $possible = 0;
        $earned   = 0;

        foreach ($checks as $check) {
            $possible += (int) $check['weight'];

            if (!empty($check['ok'])) {
                $earned += (int) $check['weight'];
            }
        }

        if ($possible <= 0) {
            return 0;
        }

        return (int) round(($earned / $possible) * 100);
    }

    public static function stars($score) {
        if ($score >= 90) {
            return '⭐⭐⭐⭐⭐';
        }

        if ($score >= 70) {
            return '⭐⭐⭐⭐☆';
        }

        if ($score >= 50) {
            return '⭐⭐⭐☆☆';
        }

        if ($score >= 30) {
            return '⭐⭐☆☆☆';
        }

        return '⭐☆☆☆☆';
    }

    public static function filled($value) {
        if (is_array($value)) {
            $value = implode('', $value);
        }

        return trim((string) $value) !== '';
    }

    public static function has_any($data, $keys) {
        foreach ($keys as $key) {
            if (self::filled($data[$key] ?? '')) {
                return true;
            }
        }

        return false;
    }
}
