<?php
use BLR\Backline\Core\Access;
use BLR\Backline\Core\Media;

if (!defined('ABSPATH')) {
    exit;
}
$base = rtrim((string) ($ctx['base_url'] ?? ''), '/') . '/';
$is_edit = ($ctx['action'] ?? '') === 'edit';
$post_id = $is_edit ? (int) ($ctx['id'] ?? 0) : 0;
$post = $is_edit ? get_post($post_id) : null;
if ($is_edit && (!$post || $post->post_type !== 'blr_track')) { echo '<div class="container-fluid p-0"><div class="alert alert-danger">' . esc_html__('Track not found.', 'blr-backline') . '</div></div>'; return; }
if ($is_edit && !Access::can_edit_post($post_id, 'blr_track')) { echo '<div class="container-fluid p-0"><div class="alert alert-danger">' . esc_html__('You do not have permission to edit this track.', 'blr-backline') . '</div></div>'; return; }
if (!$is_edit && !Access::can_create_post_type('blr_track')) { echo '<div class="container-fluid p-0"><div class="alert alert-danger">' . esc_html__('You do not have permission to create tracks.', 'blr-backline') . '</div></div>'; return; }
// phpcs:disable WordPress.Security.NonceVerification.Recommended
$saved_notice = isset($_GET['saved']) ? absint((string) wp_unslash($_GET['saved'])) : 0;
$errors = isset($ctx['errors']) && is_array($ctx['errors']) ? $ctx['errors'] : [];
// phpcs:enable WordPress.Security.NonceVerification.Recommended
$getm = static function (string $key) use ($post_id): string { return $post_id ? (string) get_post_meta($post_id, $key, true) : ''; };
$title_v = $post ? (string) $post->post_title : '';
$content_v = $post ? (string) $post->post_content : '';
$audio_url = $getm('blr_audio_url');
$current_audio_attachment_id = $post_id ? absint(get_post_meta($post_id, 'blr_audio_attachment_id', true)) : 0;
$current_image_id = $post_id ? absint(get_post_thumbnail_id($post_id)) : 0;
$release_status_terms = $post_id ? wp_get_object_terms($post_id, 'blr_release_status', ['fields' => 'ids']) : [];
$release_status_selected = (!is_wp_error($release_status_terms) && !empty($release_status_terms)) ? (int) $release_status_terms[0] : 0;
$release_status_options = get_terms(['taxonomy' => 'blr_release_status', 'hide_empty' => false]);
$release_status_options = is_wp_error($release_status_options) ? [] : $release_status_options;
?>
<div class="container-fluid p-0">
  <div class="d-flex align-items-center justify-content-between mb-3"><h1 class="h3 mb-0"><?php echo $is_edit ? esc_html__('Edit Track', 'blr-backline') : esc_html__('New Track', 'blr-backline'); ?></h1><a class="btn btn-outline-secondary" href="<?php echo esc_url($base . 'tracks/'); ?>"><?php echo esc_html__('Back', 'blr-backline'); ?></a></div>
  <?php if ($saved_notice): ?><div class="alert alert-success"><?php echo esc_html__('Saved.', 'blr-backline'); ?></div><?php endif; ?>
  <?php foreach ($errors as $error): ?><div class="alert alert-danger"><?php echo esc_html((string) $error); ?></div><?php endforeach; ?>
  <div class="card"><div class="card-body"><form method="post" enctype="multipart/form-data"><?php wp_nonce_field('blr_ba_save_track'); ?>
    <div class="row g-3">
      <div class="col-12 col-lg-8">
        <div class="mb-3"><label class="form-label"><?php echo esc_html__('Title', 'blr-backline'); ?></label><input class="form-control" type="text" name="title" value="<?php echo esc_attr($title_v); ?>" required></div>
        <div class="mb-3"><label class="form-label"><?php echo esc_html__('Notes / Description', 'blr-backline'); ?></label><textarea class="form-control" name="content" rows="6"><?php echo esc_textarea($content_v); ?></textarea></div>
        <h5 class="mb-3"><?php echo esc_html__('Audio File', 'blr-backline'); ?></h5>
        <div id="blr-ba-track-audio-preview" class="mb-3 blr-ba-audio-preview"><?php echo wp_kses_post(Media::audio_preview_markup($current_audio_attachment_id, $audio_url)); ?></div>

        <div class="mb-3">
          <label class="form-label"><?php echo esc_html__('Existing Audio Files', 'blr-backline'); ?></label>
          <div>
            <button
              class="btn btn-outline-secondary"
              type="button"
              data-bs-toggle="modal"
              data-bs-target="#blr-ba-track-audio-modal"
            >
              <?php echo esc_html__('Choose Existing Audio', 'blr-backline'); ?>
            </button>
          </div>
        </div>

        <div
          class="modal fade"
          id="blr-ba-track-audio-modal"
          tabindex="-1"
          aria-labelledby="blr-ba-track-audio-modal-label"
          aria-hidden="true"
        >
          <div class="modal-dialog modal-xl modal-dialog-scrollable">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="blr-ba-track-audio-modal-label">
                  <?php echo esc_html__('Choose Existing Audio', 'blr-backline'); ?>
                </h5>
                <button
                  type="button"
                  class="btn-close"
                  data-bs-dismiss="modal"
                  aria-label="<?php echo esc_attr__('Close', 'blr-backline'); ?>"
                ></button>
              </div>

              <div class="modal-body">
                <?php
                Media::render_audio_visual_picker(
                    'track_audio_attachment_id',
                    [
                        'selected'           => $current_audio_attachment_id,
                        'allow_none'         => true,
                        'none_label'         => __('No Audio File', 'blr-backline'),
                        'search_placeholder' => __('Search audio files...', 'blr-backline'),
                        'preview_target'     => '#blr-ba-track-audio-preview',
                    ]
                );
                ?>
              </div>

              <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                  <?php echo esc_html__('Cancel', 'blr-backline'); ?>
                </button>
              </div>
            </div>
          </div>
        </div>

        <div class="mb-3">
          <label class="form-label"><?php echo esc_html__('Upload New Audio File', 'blr-backline'); ?></label>
          <input class="form-control blr-ba-audio-input" type="file" name="audio_file" accept="audio/*" data-preview="#blr-ba-track-audio-preview">
          <?php if ($audio_url): ?><div class="form-text mt-2"><a href="<?php echo esc_url($audio_url); ?>" target="_blank" rel="noopener"><?php echo esc_html__('Current audio file', 'blr-backline'); ?></a></div><?php endif; ?>
        </div>

        <div class="row g-3">
          <div class="col-md-6"><label class="form-label"><?php echo esc_html__('Audio URL', 'blr-backline'); ?></label><input class="form-control" type="url" name="blr_audio_url" value="<?php echo esc_attr($audio_url); ?>"></div>
          <div class="col-md-6"><label class="form-label"><?php echo esc_html__('Release Status', 'blr-backline'); ?></label><select class="form-select blr-ba-select2" name="blr_release_status_term"><option value=""></option><?php foreach ($release_status_options as $term): if ($term instanceof WP_Term): ?><option value="<?php echo esc_attr((string) $term->term_id); ?>" <?php selected($release_status_selected, (int) $term->term_id); ?>><?php echo esc_html($term->name); ?></option><?php endif; endforeach; ?></select></div>
          <div class="col-md-6"><label class="form-label"><?php echo esc_html__('Release Date', 'blr-backline'); ?></label><input class="form-control blr-ba-date" type="text" name="blr_release_date" value="<?php echo esc_attr($getm('blr_release_date')); ?>"></div>
          <div class="col-md-6"><label class="form-label"><?php echo esc_html__('Artist', 'blr-backline'); ?></label><input class="form-control" type="text" name="blr_artist" value="<?php echo esc_attr($getm('blr_artist')); ?>"></div>
          <div class="col-md-4"><label class="form-label"><?php echo esc_html__('Duration', 'blr-backline'); ?></label><input class="form-control" type="text" name="blr_duration" value="<?php echo esc_attr($getm('blr_duration')); ?>"></div>
          <div class="col-md-4"><label class="form-label"><?php echo esc_html__('BPM', 'blr-backline'); ?></label><input class="form-control" type="number" name="blr_bpm" value="<?php echo esc_attr($getm('blr_bpm')); ?>"></div>
          <div class="col-md-4"><label class="form-label"><?php echo esc_html__('Key', 'blr-backline'); ?></label><input class="form-control" type="text" name="blr_key" value="<?php echo esc_attr($getm('blr_key')); ?>"></div>
          <div class="col-md-6"><label class="form-label"><?php echo esc_html__('ISRC', 'blr-backline'); ?></label><input class="form-control" type="text" name="blr_isrc" value="<?php echo esc_attr($getm('blr_isrc')); ?>"></div>
          <div class="col-md-6"><label class="form-label"><?php echo esc_html__('UPC', 'blr-backline'); ?></label><input class="form-control" type="text" name="blr_upc" value="<?php echo esc_attr($getm('blr_upc')); ?>"></div>
          <div class="col-md-6"><label class="form-label"><?php echo esc_html__('Spotify URL', 'blr-backline'); ?></label><input class="form-control" type="url" name="blr_spotify_url" value="<?php echo esc_attr($getm('blr_spotify_url')); ?>"></div>
          <div class="col-md-6"><label class="form-label"><?php echo esc_html__('Apple Music URL', 'blr-backline'); ?></label><input class="form-control" type="url" name="blr_apple_music_url" value="<?php echo esc_attr($getm('blr_apple_music_url')); ?>"></div>
          <div class="col-md-6"><label class="form-label"><?php echo esc_html__('Bandcamp URL', 'blr-backline'); ?></label><input class="form-control" type="url" name="blr_bandcamp_url" value="<?php echo esc_attr($getm('blr_bandcamp_url')); ?>"></div>
          <div class="col-md-6"><label class="form-label"><?php echo esc_html__('YouTube URL', 'blr-backline'); ?></label><input class="form-control" type="url" name="blr_youtube_url" value="<?php echo esc_attr($getm('blr_youtube_url')); ?>"></div>
          <div class="col-md-6"><label class="form-label"><?php echo esc_html__('SoundCloud URL', 'blr-backline'); ?></label><input class="form-control" type="url" name="blr_soundcloud_url" value="<?php echo esc_attr($getm('blr_soundcloud_url')); ?>"></div>
          <div class="col-12"><label class="form-label"><?php echo esc_html__('Release Notes', 'blr-backline'); ?></label><textarea class="form-control" name="blr_release_notes" rows="4"><?php echo esc_textarea($getm('blr_release_notes')); ?></textarea></div>
        </div>
      </div>
      <div class="col-12 col-lg-4">
        <h5 class="mb-3"><?php echo esc_html__('Track Image', 'blr-backline'); ?></h5>
          <div id="blr-ba-track-image-preview" class="mb-3 blr-ba-visual-preview blr-ba-visual-preview--fixed"><?php echo wp_kses_post(Media::preview_markup($current_image_id, 'large')); ?></div>

          <div class="mb-3">
            <label class="form-label"><?php echo esc_html__('Existing Images', 'blr-backline'); ?></label>
            <div>
              <button
                class="btn btn-outline-secondary blr-ch-img-btn"
                type="button"
                data-bs-toggle="modal"
                data-bs-target="#blr-ba-track-image-modal"
              >
                <?php echo esc_html__('Choose Existing Image', 'blr-backline'); ?>
              </button>
            </div>
          </div>

          <div
            class="modal fade"
            id="blr-ba-track-image-modal"
            tabindex="-1"
            aria-labelledby="blr-ba-track-image-modal-label"
            aria-hidden="true"
          >
            <div class="modal-dialog modal-xl modal-dialog-scrollable">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="blr-ba-track-image-modal-label">
                    <?php echo esc_html__('Choose Existing Image', 'blr-backline'); ?>
                  </h5>
                  <button
                    type="button"
                    class="btn-close"
                    data-bs-dismiss="modal"
                    aria-label="<?php echo esc_attr__('Close', 'blr-backline'); ?>"
                  ></button>
                </div>

                <div class="modal-body">
                  <?php
                  Media::render_visual_picker(
                      'track_image_id',
                      [
                          'selected'           => $current_image_id,
                          'allow_none'         => true,
                          'none_label'         => __('No Image', 'blr-backline'),
                          'search_placeholder' => __('Search images...', 'blr-backline'),
                          'preview_target'     => '#blr-ba-track-image-preview',
                      ]
                  );
                  ?>
                </div>

                <div class="modal-footer">
                  <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                    <?php echo esc_html__('Cancel', 'blr-backline'); ?>
                  </button>
                </div>
              </div>
            </div>
          </div>

          <div class="mb-3">
            <label class="form-label"><?php echo esc_html__('Upload New Image', 'blr-backline'); ?></label>
            <input class="form-control blr-ba-image-input" type="file" name="track_image_file" accept="image/*" data-preview="#blr-ba-track-image-preview">
          </div>
      </div>
    </div>
    <div class="mt-4"><button class="btn btn-primary" type="submit"><?php echo esc_html__('Save Track', 'blr-backline'); ?></button></div>
  </form></div></div>
</div>
