<?php

declare(strict_types=1);
defined('ABSPATH') || exit;

class DSProofwp_Media_Controller
{
    private const ROUTE_NAMESPACE = 'dsproofwp/v1';
    private DSProofwp_Form_Settings_Repository $settings_repository;

    public function __construct(DSProofwp_Form_Settings_Repository $settings_repository)
    {
        $this->settings_repository = $settings_repository;
    }

    public function register_routes(): void
    {
        register_rest_route(
            self::ROUTE_NAMESPACE,
            '/media/upload',
            [
                [
                    'methods'             => WP_REST_Server::CREATABLE,
                    'callback'            => [$this, 'upload_media'],
                    'permission_callback' => '__return_true',
                ],
            ]
        );
    }

    public function upload_media(WP_REST_Request $request)
    {
        if (empty($_FILES['file'])) {
            return new WP_Error('dsproofwp_no_file', 'No file was uploaded.', ['status' => 400]);
        }

        $settings = $this->settings_repository->get();
        $file = $_FILES['file'];

        // Basic validation
        $file_type = wp_check_filetype($file['name']);
        $ext = strtolower((string) $file_type['ext']);
        
        $is_image = strpos($file['type'], 'image/') === 0;
        $is_video = strpos($file['type'], 'video/') === 0;

        if (!$is_image && !$is_video) {
             return new WP_Error('dsproofwp_invalid_type', 'Invalid file type.', ['status' => 400]);
        }

        if ($is_image) {
            $allowed_exts = array_map('trim', explode(',', $settings['allowed_image_types'] ?? 'jpg,jpeg,png,webp'));
            if (!in_array($ext, $allowed_exts, true)) {
                return new WP_Error('dsproofwp_invalid_ext', 'Extension not allowed for images.', ['status' => 400]);
            }
            $max_size = (int)($settings['image_max_size_mb'] ?? 5) * 1024 * 1024;
            if ($file['size'] > $max_size) {
                 return new WP_Error('dsproofwp_file_too_large', 'Image is too large.', ['status' => 400]);
            }
        }

        if ($is_video) {
            $allowed_exts = array_map('trim', explode(',', $settings['allowed_video_types'] ?? 'mp4,mov,webm'));
            if (!in_array($ext, $allowed_exts, true)) {
                return new WP_Error('dsproofwp_invalid_ext', 'Extension not allowed for videos.', ['status' => 400]);
            }
            $max_size = (int)($settings['video_max_size_mb'] ?? 50) * 1024 * 1024;
            if ($file['size'] > $max_size) {
                 return new WP_Error('dsproofwp_file_too_large', 'Video is too large.', ['status' => 400]);
            }
        }

        require_once ABSPATH . 'wp-admin/includes/image.php';
        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/media.php';

        $attachment_id = media_handle_upload('file', 0);

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

        return rest_ensure_response([
            'attachment_id' => $attachment_id,
            'url'           => wp_get_attachment_url($attachment_id),
            'media_type'    => $is_image ? 'image' : 'video',
        ]);
    }
}
