<?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_release')) {
    echo '<div class="container-fluid p-0"><div class="alert alert-danger">' . esc_html__('Album not found.', 'blr-backline') . '</div></div>';
    return;
}
if ($is_edit && !Access::can_edit_post($post_id, 'blr_release')) {
    echo '<div class="container-fluid p-0"><div class="alert alert-danger">' . esc_html__('You do not have permission to edit this album.', 'blr-backline') . '</div></div>';
    return;
}
if (!$is_edit && !Access::can_create_post_type('blr_release')) {
    echo '<div class="container-fluid p-0"><div class="alert alert-danger">' . esc_html__('You do not have permission to create albums.', '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 : '';
$track_ids_existing = array_values(array_filter(array_map('absint', (array) get_post_meta($post_id, 'blr_track_ids', true))));
$release_type_terms = $post_id ? wp_get_object_terms($post_id, 'blr_release_type', ['fields' => 'ids']) : [];
$release_type_selected = (!is_wp_error($release_type_terms) && !empty($release_type_terms)) ? (int) $release_type_terms[0] : 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_type_options = get_terms(['taxonomy' => 'blr_release_type', 'hide_empty' => false]);
$release_status_options = get_terms(['taxonomy' => 'blr_release_status', 'hide_empty' => false]);
$release_type_options = is_wp_error($release_type_options) ? [] : $release_type_options;
$release_status_options = is_wp_error($release_status_options) ? [] : $release_status_options;
$all_tracks = get_posts([
    'post_type' => 'blr_track',
    'post_status' => ['publish', 'draft'],
    'posts_per_page' => 500,
    'orderby' => 'date',
    'order' => 'DESC',
    'no_found_rows' => true,
]);
$loaded_track_ids = array_map(static fn($track): int => $track instanceof WP_Post ? (int) $track->ID : 0, $all_tracks);
$missing_selected_track_ids = array_values(array_diff($track_ids_existing, array_filter($loaded_track_ids)));
if (!empty($missing_selected_track_ids)) {
    $selected_tracks = get_posts([
        'post_type' => 'blr_track',
        'post_status' => ['publish', 'draft'],
        'post__in' => $missing_selected_track_ids,
        'posts_per_page' => count($missing_selected_track_ids),
        'orderby' => 'post__in',
        'no_found_rows' => true,
    ]);
    $all_tracks = array_merge($selected_tracks, $all_tracks);
}

$current_image_id = $post_id ? absint(get_post_thumbnail_id($post_id)) : 0;
?>
<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 Album', 'blr-backline') : esc_html__('New Album', 'blr-backline'); ?></h1>
    <a class="btn btn-outline-secondary" href="<?php echo esc_url($base . 'albums/'); ?>"><?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_release'); ?>
    <input type="hidden" name="track_ids_submitted" value="1">
    <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__('Description', 'blr-backline'); ?></label><textarea class="form-control" name="content" rows="6"><?php echo esc_textarea($content_v); ?></textarea></div>
        <div class="row g-3">
          <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')); ?>" placeholder="<?php echo esc_attr__('YYYY-MM-DD', 'blr-backline'); ?>"></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-6"><label class="form-label"><?php echo esc_html__('Album Type', 'blr-backline'); ?></label><select class="form-select blr-ba-select2" name="blr_release_type_term"><option value=""></option><?php foreach ($release_type_options as $term): if ($term instanceof WP_Term): ?><option value="<?php echo esc_attr((string) $term->term_id); ?>" <?php selected($release_type_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 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__('UPC', 'blr-backline'); ?></label><input class="form-control" type="text" inputmode="numeric" 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>
        <hr>
        <h5 class="mb-3"><?php echo esc_html__('Tracks', 'blr-backline'); ?></h5>
        <select class="form-select blr-ba-select2" id="blr-ba-track-select" name="track_ids[]" multiple>
          <?php foreach ($all_tracks as $track_post): ?>
            <option value="<?php echo esc_attr((string) $track_post->ID); ?>" data-edit-url="<?php echo esc_url($base . 'tracks/edit/' . (int) $track_post->ID . '/'); ?>" <?php selected(in_array((int) $track_post->ID, $track_ids_existing, true)); ?>><?php echo esc_html(get_the_title($track_post)); ?></option>
          <?php endforeach; ?>
        </select>
        <input type="hidden" name="track_order" id="blr-ba-track-order-input" value="<?php echo esc_attr(implode(',', array_map('absint', $track_ids_existing))); ?>">
        <div class="form-text mt-2"><?php echo esc_html__('Upload audio files below to create and attach new tracks automatically.', 'blr-backline'); ?></div>
        <div class="card mt-3">
          <div class="card-header"><h6 class="card-title mb-0"><?php echo esc_html__('Track Order', 'blr-backline'); ?></h6></div>
          <div class="card-body">
            <div class="small text-muted mb-2"><?php echo esc_html__('Drag tracks to set the album order.', 'blr-backline'); ?></div>
            <ul class="list-group" id="blr-ba-track-order">
              <?php foreach ($track_ids_existing as $ordered_track_id): ?>
                <?php $ordered_track = get_post($ordered_track_id); ?>
                <?php if ($ordered_track instanceof WP_Post && $ordered_track->post_type === 'blr_track'): ?>
                  <li class="list-group-item d-flex align-items-center justify-content-between" data-id="<?php echo esc_attr((string) $ordered_track_id); ?>" draggable="true">
                    <div class="d-flex align-items-center gap-2">
                      <span class="blr-ba-drag-handle blr-ba-drag-handle--grab text-muted" title="<?php echo esc_attr__('Drag to reorder', 'blr-backline'); ?>">☰</span>
                      <span class="blr-ba-track-label"><?php echo esc_html(get_the_title($ordered_track)); ?></span>
                    </div>
                    <div class="d-flex align-items-center gap-2">
                      <a class="btn btn-sm btn-outline-secondary" href="<?php echo esc_url($base . 'tracks/edit/' . (int) $ordered_track_id . '/'); ?>"><?php echo esc_html__('Edit', 'blr-backline'); ?></a>
                      <button type="button" class="btn btn-sm btn-outline-danger blr-ba-track-remove"><?php echo esc_html__('Remove', 'blr-backline'); ?></button>
                    </div>
                  </li>
                <?php endif; ?>
              <?php endforeach; ?>
            </ul>
          </div>
        </div>
        <div class="mt-3"><label class="form-label"><?php echo esc_html__('Upload Audio Files', 'blr-backline'); ?></label><input class="form-control" type="file" name="audio_files[]" multiple accept="audio/*"></div>
      </div>
      <div class="col-12 col-lg-4">
        <h5 class="mb-3"><?php echo esc_html__('Cover Image', 'blr-backline'); ?></h5>
        <div id="blr-ba-release-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-release-image-modal"
    >
      <?php echo esc_html__('Choose Existing Image', 'blr-backline'); ?>
    </button>
  </div>
</div>

<div
  class="modal fade"
  id="blr-ba-release-image-modal"
  tabindex="-1"
  aria-labelledby="blr-ba-release-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-release-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(
            'cover_image_id',
            [
                'selected'           => $current_image_id,
                'allow_none'         => true,
                'none_label'         => __('No Cover Image', 'blr-backline'),
                'search_placeholder' => __('Search images...', 'blr-backline'),
                'preview_target'     => '#blr-ba-release-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 Cover Image', 'blr-backline'); ?></label>
          <input class="form-control blr-ba-image-input" type="file" name="cover_image" accept="image/*" data-preview="#blr-ba-release-image-preview">
        </div>
      </div>
    </div>
    <div class="mt-4"><button class="btn btn-primary" type="submit"><?php echo esc_html__('Save Album', 'blr-backline'); ?></button></div>
  </form></div></div>
</div>
