<?php

namespace Silvanus\blocks\sliders\ImageSlider;

use Silvanus\includes\blocks\BlockModuleInterface;

final class Module implements BlockModuleInterface
{
    public function register(): void
    {
        add_filter('acf/validate_value/key=field_image_slider_slides', [$this, 'validateSlides'], 10, 4);
    }

    public function validateSlides($valid, $value, $field, $input)
    {
        if ($valid !== true) {
            return $valid;
        }

        if (empty($value) || !is_array($value)) {
            return $valid;
        }

        $imageKey = 'field_image_slider_image';
        $videoKey = 'field_image_slider_video';

        if (!empty($field['sub_fields']) && is_array($field['sub_fields'])) {
            foreach ($field['sub_fields'] as $sf) {
                if (($sf['name'] ?? '') === 'image') {
                    $imageKey = $sf['key'] ?? $imageKey;
                }
                if (($sf['name'] ?? '') === 'video') {
                    $videoKey = $sf['key'] ?? $videoKey;
                }
            }
        }

        foreach ($value as $i => $row) {
            if (!is_array($row)) {
                continue;
            }

            $imageVal = $row[$imageKey] ?? $row['image'] ?? null;
            $videoVal = $row[$videoKey] ?? $row['video'] ?? null;

            $hasImage = is_numeric($imageVal) && (int)$imageVal > 0;
            $hasVideo = is_array($videoVal) ? !empty($videoVal['url']) : !empty($videoVal);

            if (($hasImage && $hasVideo) || (!$hasImage && !$hasVideo)) {
                $rowNumber = is_numeric($i) ? ((int)$i + 1) : '';
                return 'Slide' . ($rowNumber ? ' #' . $rowNumber : '') . ': please add either an Image OR a Video (not both).';
            }
        }

        return $valid;
    }
}