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

class BMTQB_Photo_Uploader {
    public static function validate_request(BMTQB_Industry_Interface $industry, $files) {
        $uploaded_count = 0;
        $definitions = $industry->photo_definitions();

        foreach ($definitions as $key => $definition) {
            $error = self::file_error($files, $key);

            if ($error === UPLOAD_ERR_NO_FILE) {
                continue;
            }

            if ($error !== UPLOAD_ERR_OK) {
                return new WP_Error('bmtqb_photo_upload_error', 'One or more photos could not be uploaded. Please try again.');
            }

            $uploaded_count++;
        }

        if ($uploaded_count > 0 && $uploaded_count < count($definitions)) {
            return new WP_Error('bmtqb_photos_incomplete', 'Please upload all requested photos, or leave all photo fields blank.');
        }

        return true;
    }

    public static function handle_uploads(BMTQB_Industry_Interface $industry, $post_id, $files) {
        $validation = self::validate_request($industry, $files);
        if (is_wp_error($validation)) {
            return $validation;
        }

        if (!self::has_any_upload($industry, $files)) {
            return [];
        }

        if (!function_exists('wp_handle_upload')) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
        }

        $photos = [];
        $allowed_mimes = [
            'jpg|jpeg|jpe' => 'image/jpeg',
            'png' => 'image/png',
            'webp' => 'image/webp',
            'heic' => 'image/heic',
            'heif' => 'image/heif',
        ];

        foreach ($industry->photo_definitions() as $key => $definition) {
            $file = self::extract_file($files, $key);

            if (empty($file)) {
                continue;
            }

            $upload = wp_handle_upload($file, [
                'test_form' => false,
                'mimes' => $allowed_mimes,
            ]);

            if (!empty($upload['error'])) {
                return new WP_Error('bmtqb_photo_upload_failed', $upload['error']);
            }

            $photos[$key] = [
                'key' => $key,
                'label' => $definition['label'] ?? $key,
                'name' => sanitize_file_name($file['name']),
                'path' => $upload['file'] ?? '',
                'url' => $upload['url'] ?? '',
                'type' => $upload['type'] ?? '',
            ];
        }

        update_post_meta($post_id, '_' . $industry->meta_prefix() . '_photos', $photos);

        return $photos;
    }

    public static function attachment_paths($photos) {
        if (empty($photos) || !is_array($photos)) {
            return [];
        }

        $paths = [];
        foreach ($photos as $photo) {
            if (!empty($photo['path']) && file_exists($photo['path'])) {
                $paths[] = $photo['path'];
            }
        }

        return $paths;
    }

    public static function has_any_upload(BMTQB_Industry_Interface $industry, $files) {
        foreach ($industry->photo_definitions() as $key => $definition) {
            if (self::file_error($files, $key) === UPLOAD_ERR_OK) {
                return true;
            }
        }

        return false;
    }

    private static function file_error($files, $key) {
        if (!isset($files['photos']['error'][$key])) {
            return UPLOAD_ERR_NO_FILE;
        }

        return (int) $files['photos']['error'][$key];
    }

    private static function extract_file($files, $key) {
        if (self::file_error($files, $key) !== UPLOAD_ERR_OK) {
            return [];
        }

        return [
            'name' => $files['photos']['name'][$key] ?? '',
            'type' => $files['photos']['type'][$key] ?? '',
            'tmp_name' => $files['photos']['tmp_name'][$key] ?? '',
            'error' => $files['photos']['error'][$key] ?? UPLOAD_ERR_NO_FILE,
            'size' => $files['photos']['size'][$key] ?? 0,
        ];
    }
}
