<?php
namespace BLR\Backline\Core;

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

final class TrackBulkUpload {
    public const ACTION = 'bulk_track_upload';
    private const NONCE_ACTION = 'blr_ba_bulk_track_upload';

    public static function handle_submission(string $redirect_url): void {
        $request_method = strtoupper(sanitize_text_field((string) wp_unslash($_SERVER['REQUEST_METHOD'] ?? 'GET')));
        if ($request_method !== 'POST') {
            return;
        }

        $action = isset($_POST['blr_ba_action']) ? sanitize_text_field(wp_unslash($_POST['blr_ba_action'])) : '';
        if ($action !== self::ACTION) {
            return;
        }

        if (!Access::can_create_post_type('blr_track')) {
            wp_die(esc_html__('You do not have permission to upload tracks.', 'blr-backline'));
        }
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field((string) wp_unslash($_POST['_wpnonce'])) : '';
        if ($nonce === '' || !wp_verify_nonce($nonce, self::NONCE_ACTION)) {
            wp_die(esc_html__('Security check failed.', 'blr-backline'));
        }

        $selected_upload_count = CrudHelpers::count_selected_uploads('audio_files');
        $uploads = CrudHelpers::handle_multi_upload('audio_files', 0, CrudHelpers::audio_mimes(), CrudHelpers::audio_max_file_size());

        $created = 0;
        $failed = max(0, $selected_upload_count - count($uploads));

        foreach ($uploads as $upload) {
            $track_id = self::create_track_from_upload($upload);

            if ($track_id > 0) {
                $created++;
            } else {
                $failed++;
                CrudHelpers::cleanup_upload_result($upload);
            }
        }

        $redirect_url = add_query_arg([
            'bulk_uploaded' => 1,
            'bulk_created'  => $created,
            'bulk_failed'   => $failed,
        ], $redirect_url);

        CrudHelpers::redirect($redirect_url);
    }

    public static function maybe_handle_submission(string $redirect_url): void {
        self::handle_submission($redirect_url);
    }

    public static function render_notices(): void {
        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only query args used for post-redirect notices.
        $bulk_uploaded = isset($_GET['bulk_uploaded']) ? absint((string) wp_unslash($_GET['bulk_uploaded'])) : 0;
        if (!$bulk_uploaded) {
            return;
        }

        $created = isset($_GET['bulk_created']) ? max(0, absint((string) wp_unslash($_GET['bulk_created']))) : 0;
        $failed = isset($_GET['bulk_failed']) ? max(0, absint((string) wp_unslash($_GET['bulk_failed']))) : 0;
        // phpcs:enable WordPress.Security.NonceVerification.Recommended

        if ($created > 0) {
            $label = $created === 1 ? __('track', 'blr-backline') : __('tracks', 'blr-backline');
            echo '<div class="alert alert-success">';
            /* translators: 1: number of created tracks, 2: singular or plural track label. */
            echo esc_html(sprintf(__('Upload complete. %1$d %2$s created.', 'blr-backline'), $created, $label));
            echo '</div>';
        }

        if ($created === 0 && $failed === 0) {
            echo '<div class="alert alert-warning">';
            echo esc_html__('No audio files were uploaded.', 'blr-backline');
            echo '</div>';
            return;
        }

        if ($failed > 0) {
            $label = $failed === 1 ? __('file', 'blr-backline') : __('files', 'blr-backline');
            echo '<div class="alert alert-warning">';
            /* translators: 1: number of files that failed, 2: singular or plural file label. */
            echo esc_html(sprintf(__('%1$d %2$s could not be turned into tracks.', 'blr-backline'), $failed, $label));
            echo '</div>';
        }
    }

    public static function render_toggle_button(string $target_id, array $args = []): void {
        $label = (string)($args['label'] ?? __('Upload Tracks', 'blr-backline'));
        $class = (string)($args['class'] ?? 'btn btn-outline-primary');

        ?>
        <button
          class="<?php echo esc_attr($class); ?>"
          type="button"
          onclick="(function(){var el=document.getElementById('<?php echo esc_js($target_id); ?>'); if(!el){return;} el.classList.toggle('d-none');})();"
        >
          <?php echo esc_html($label); ?>
        </button>
        <?php
    }

    public static function render_form(string $action_url): void {
        self::render_form_panel(
            $action_url,
            'blr-ba-track-bulk-upload-form',
            [
                'panel_class' => 'border-0 bg-transparent',
                'show'        => true,
            ]
        );
    }

    public static function render_form_panel(string $action_url, string $target_id, array $args = []): void {
        $title = (string)($args['title'] ?? __('Upload Audio Files', 'blr-backline'));
        $panel_class = (string)($args['panel_class'] ?? 'card border d-none');
        $input_name = (string)($args['input_name'] ?? 'audio_files[]');
        $input_label = (string)($args['input_label'] ?? __('Audio files', 'blr-backline'));
        $help_text = (string)($args['help_text'] ?? __('Each uploaded file becomes its own published Track. Titles are generated from filenames.', 'blr-backline'));
        $submit_label = (string)($args['submit_label'] ?? __('Upload and Create Tracks', 'blr-backline'));
        $cancel_label = (string)($args['cancel_label'] ?? __('Cancel', 'blr-backline'));
        $show = !empty($args['show']);

        if ($show && strpos($panel_class, 'd-none') !== false) {
            $panel_class = trim(str_replace('d-none', '', $panel_class));
        }
        ?>
        <div id="<?php echo esc_attr($target_id); ?>" class="<?php echo esc_attr(trim($panel_class)); ?>">
          <div class="card-body">
            <h6 class="mb-3"><?php echo esc_html($title); ?></h6>

            <form method="post" action="<?php echo esc_url($action_url); ?>" enctype="multipart/form-data">
              <?php wp_nonce_field(self::NONCE_ACTION); ?>
              <input type="hidden" name="blr_ba_action" value="<?php echo esc_attr(self::ACTION); ?>">

              <div class="mb-3">
                <label class="form-label"><?php echo esc_html($input_label); ?></label>
                <input
                  class="form-control"
                  type="file"
                  name="<?php echo esc_attr($input_name); ?>"
                  multiple
                  accept="audio/*"
                  required
                >
                <div class="form-text"><?php echo esc_html($help_text); ?></div>
              </div>


              <div class="d-flex gap-2">
                <button class="btn btn-primary" type="submit"><?php echo esc_html($submit_label); ?></button>
                <button
                  class="btn btn-outline-secondary"
                  type="button"
                  onclick="(function(){var el=document.getElementById('<?php echo esc_js($target_id); ?>'); if(!el){return;} el.classList.add('d-none');})();"
                >
                  <?php echo esc_html($cancel_label); ?>
                </button>
              </div>
            </form>
          </div>
        </div>
        <?php
    }

    private static function create_track_from_upload(array $upload): int {
        $filename = (string)($upload['filename'] ?? '');
        $title = self::filename_to_title($filename);
        if ($title === '') {
            $title = __('New Track', 'blr-backline');
        }

        $track_id = wp_insert_post(wp_slash([
            'post_title'   => $title,
            'post_status'  => 'publish',
            'post_type'    => 'blr_track',
            'post_content' => '',
        ]), true);

        if (is_wp_error($track_id) || !$track_id) {
            return 0;
        }

        $track_id = (int) $track_id;

        $audio_url = (string)($upload['url'] ?? '');
        if ($audio_url !== '') {
            update_post_meta($track_id, 'blr_audio_url', $audio_url);
        }

        $attachment_id = absint($upload['attachment_id'] ?? 0);
        if ($attachment_id > 0) {
            update_post_meta($track_id, 'blr_audio_attachment_id', $attachment_id);
            Media::mark_attachment_as_post_owned($attachment_id, $track_id, 'track_audio');

            $duration = CrudHelpers::attachment_duration($attachment_id);
            if ($duration !== '') {
                update_post_meta($track_id, 'blr_duration', $duration);
            }
        }

        return $track_id;
    }

    private static function filename_to_title(string $filename): string {
        $filename = wp_basename($filename);
        $title = preg_replace('/\.[^.]+$/', '', $filename);
        $title = is_string($title) ? $title : '';
        $title = str_replace(['_', '-'], ' ', $title);
        $title = preg_replace('/\s+/', ' ', $title);
        $title = trim((string) $title);

        return sanitize_text_field($title);
    }

}
