<?php
/**
 * Flatsome functions and definitions
 *
 * @package flatsome
 */

require get_template_directory() . '/inc/init.php';

Flatsome()->init();

/**
 * It's not recommended to add any custom code here. Please use a child theme
 * so that your customizations aren't lost during updates.
 *
 * Learn more here: https://developer.wordpress.org/themes/advanced-topics/child-themes/
 */

// TSP Save Submission
add_action('wp_ajax_tsp_save_submission', function(){
    if(!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'tsp_nonce')) {
        wp_send_json_error('Invalid nonce');
    }
    $user = wp_get_current_user();
    if(!$user->ID) wp_send_json_error('Not logged in');

    // Required field validation
    $tsp_required = [
        'song_title'    => 'Song title',
        'artist'        => 'Songwriter name',
        'genre'         => 'Genre',
        'pro'           => 'PRO',
        'cowriters'     => 'Co-writer(s)',
        'ownership_pct' => 'Ownership percentage',
    ];
    foreach($tsp_required as $tsp_k => $tsp_label){
        if(trim((string)($_POST[$tsp_k] ?? '')) === ''){
            wp_send_json_error($tsp_label.' is required.');
        }
    }
    if(empty($_FILES['audio_file']['name'])) wp_send_json_error('An audio file is required.');
    if(empty($_FILES['lyric_file']['name'])) wp_send_json_error('A lyric sheet is required.');

    // Handle audio file upload
    $audio_url = '';
    $audio_id  = 0;
    if(!empty($_FILES['audio_file']['name'])){
        require_once ABSPATH.'wp-admin/includes/file.php';
        require_once ABSPATH.'wp-admin/includes/media.php';
        require_once ABSPATH.'wp-admin/includes/image.php';
        $upload = wp_handle_upload($_FILES['audio_file'], ['test_form' => false]);
        if(!isset($upload['error'])){
            $attachment_id = wp_insert_attachment([
                'post_mime_type' => $upload['type'],
                'post_title'     => sanitize_file_name($_FILES['audio_file']['name']),
                'post_status'    => 'private',
            ], $upload['file']);
            if(!is_wp_error($attachment_id)){
                $audio_id  = $attachment_id;
                $audio_url = $upload['url'];
            }
        }
    }

    // Handle lyric sheet upload
    $lyric_url = '';
    $lyric_id  = 0;
    if(!empty($_FILES['lyric_file']['name'])){
        require_once ABSPATH.'wp-admin/includes/file.php';
        require_once ABSPATH.'wp-admin/includes/media.php';
        require_once ABSPATH.'wp-admin/includes/image.php';
        $lyric_upload = wp_handle_upload($_FILES['lyric_file'], ['test_form' => false]);
        if(!isset($lyric_upload['error'])){
            $lyric_attachment_id = wp_insert_attachment([
                'post_mime_type' => $lyric_upload['type'],
                'post_title'     => sanitize_file_name($_FILES['lyric_file']['name']),
                'post_status'    => 'private',
            ], $lyric_upload['file']);
            if(!is_wp_error($lyric_attachment_id)){
                $lyric_id  = $lyric_attachment_id;
                $lyric_url = $lyric_upload['url'];
            }
        }
    }

    $submission = [
        'song_title' => sanitize_text_field($_POST['song_title'] ?? ''),
        'artist'     => sanitize_text_field($_POST['artist']     ?? ''),
        'genre'      => sanitize_text_field($_POST['genre']      ?? ''),
        'pro'        => sanitize_text_field($_POST['pro']        ?? ''),
        'cowriters'  => sanitize_text_field($_POST['cowriters']  ?? ''),
        'ownership_pct' => sanitize_text_field($_POST['ownership_pct'] ?? ''),
        'notes'      => sanitize_textarea_field($_POST['notes']  ?? ''),
        'date'       => current_time('c'),
        'status'     => 'pending',
        'audio_url'  => $audio_url,
        'audio_id'   => $audio_id,
        'lyric_url'  => $lyric_url,
        'lyric_id'   => $lyric_id,
        'user_id'    => $user->ID,
    ];

    $submissions = get_user_meta($user->ID, 'tsp_submissions', true) ?: [];
    $submissions[] = $submission;
    update_user_meta($user->ID, 'tsp_submissions', $submissions);
    $used = (int)get_user_meta($user->ID, 'tsp_slots_used', true);
    update_user_meta($user->ID, 'tsp_slots_used', $used + 1);

    $headers = [
        'Content-Type: text/html; charset=UTF-8',
        'From: The Song Plug <info@thesongplug.com>',
    ];

    // Email to member
    $member_subject = 'Your submission has been received — ' . $submission['song_title'];
    $member_body = '
    <div style="font-family:sans-serif;max-width:600px;margin:0 auto;background:#1e1e32;color:#fff;padding:40px;border-radius:12px">
      <h2 style="color:#fff;margin:0 0 8px">Song Received ✓</h2>
      <p style="color:rgba(255,255,255,0.7);margin:0 0 24px">Thanks '.$user->display_name.' — your submission is in. Our A&R team will review it and update your status in the member dashboard.</p>
      <table style="width:100%;border-collapse:collapse;margin-bottom:28px">
        <tr><td style="padding:10px 0;border-bottom:1px solid rgba(255,255,255,0.1);color:rgba(255,255,255,0.5);font-size:12px">SONG TITLE</td><td style="padding:10px 0;border-bottom:1px solid rgba(255,255,255,0.1);color:#fff;font-weight:600">'.$submission['song_title'].'</td></tr>
        <tr><td style="padding:10px 0;border-bottom:1px solid rgba(255,255,255,0.1);color:rgba(255,255,255,0.5);font-size:12px">ARTIST</td><td style="padding:10px 0;border-bottom:1px solid rgba(255,255,255,0.1);color:#fff">'.$submission['artist'].'</td></tr>
        <tr><td style="padding:10px 0;border-bottom:1px solid rgba(255,255,255,0.1);color:rgba(255,255,255,0.5);font-size:12px">GENRE</td><td style="padding:10px 0;border-bottom:1px solid rgba(255,255,255,0.1);color:#fff">'.$submission['genre'].'</td></tr>
        <tr><td style="padding:10px 0;color:rgba(255,255,255,0.5);font-size:12px">DATE</td><td style="padding:10px 0;color:#fff">'.date('F j, Y', strtotime($submission['date'])).'</td></tr>
      </table>
      <a href="https://thesongplug.wpcomstaging.com/member-dashboard/" style="display:inline-block;background:#fff;color:#1e1e32;padding:12px 28px;font-weight:700;border-radius:6px;text-decoration:none;font-size:14px">VIEW MY DASHBOARD →</a>
      <p style="color:rgba(255,255,255,0.4);font-size:12px;margin-top:32px">Questions? Email us at <a href="mailto:info@thesongplug.com" style="color:rgba(255,255,255,0.6)">info@thesongplug.com</a></p>
    </div>';
    wp_mail($user->user_email, $member_subject, $member_body, $headers);

    // Email to admin
    $admin_subject = 'New Submission: ' . $submission['song_title'] . ' by ' . $submission['artist'];
    $admin_body = '
    <div style="font-family:sans-serif;max-width:600px;margin:0 auto;padding:32px;background:#f9f9f9;border-radius:8px">
      <h2 style="margin:0 0 16px">New Song Submission</h2>
      <table style="width:100%;border-collapse:collapse">
        <tr><td style="padding:8px 0;border-bottom:1px solid #eee;color:#888;font-size:12px">MEMBER</td><td style="padding:8px 0;border-bottom:1px solid #eee;font-weight:600">'.$user->display_name.' &lt;'.$user->user_email.'&gt;</td></tr>
        <tr><td style="padding:8px 0;border-bottom:1px solid #eee;color:#888;font-size:12px">SONG TITLE</td><td style="padding:8px 0;border-bottom:1px solid #eee">'.$submission['song_title'].'</td></tr>
        <tr><td style="padding:8px 0;border-bottom:1px solid #eee;color:#888;font-size:12px">ARTIST</td><td style="padding:8px 0;border-bottom:1px solid #eee">'.$submission['artist'].'</td></tr>
        <tr><td style="padding:8px 0;border-bottom:1px solid #eee;color:#888;font-size:12px">GENRE</td><td style="padding:8px 0;border-bottom:1px solid #eee">'.$submission['genre'].'</td></tr>
        <tr><td style="padding:8px 0;border-bottom:1px solid #eee;color:#888;font-size:12px">PRO</td><td style="padding:8px 0;border-bottom:1px solid #eee">'.($submission['pro'] ?: '—').'</td></tr>
        <tr><td style="padding:8px 0;border-bottom:1px solid #eee;color:#888;font-size:12px">CO-WRITER(S)</td><td style="padding:8px 0;border-bottom:1px solid #eee">'.($submission['cowriters'] ?: '—').'</td></tr>
        <tr><td style="padding:8px 0;border-bottom:1px solid #eee;color:#888;font-size:12px">OWNERSHIP</td><td style="padding:8px 0;border-bottom:1px solid #eee">'.($submission['ownership_pct'] !== '' ? $submission['ownership_pct'].'%' : '—').'</td></tr>
        <tr><td style="padding:8px 0;color:#888;font-size:12px;vertical-align:top">NOTES</td><td style="padding:8px 0">'.nl2br(esc_html($submission['notes'] ?: '—')).'</td></tr>
      </table>
      <p style="margin-top:24px;font-size:12px;color:#aaa">Submitted '.date('F j, Y g:i A', strtotime($submission['date'])).'</p>
    </div>';
    wp_mail('info@thesongplug.com', $admin_subject, $admin_body, $headers);

    wp_send_json_success();
});

// TSP Update Submission Status
add_action('wp_ajax_tsp_update_status', function(){
    if(!current_user_can('manage_options')) wp_send_json_error('Unauthorized');
    if(!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'tsp_admin_nonce')) wp_send_json_error('Invalid nonce');

    $user_id = (int)($_POST['user_id'] ?? 0);
    $index   = (int)($_POST['index']   ?? -1);
    $status  = sanitize_text_field($_POST['status'] ?? '');

    if(!$user_id || $index < 0 || !in_array($status, ['pending','reviewed','pitched','placed'])){
        wp_send_json_error('Invalid data');
    }

    $submissions = get_user_meta($user_id, 'tsp_submissions', true) ?: [];
    if(!isset($submissions[$index])) wp_send_json_error('Submission not found');

    $submissions[$index]['status'] = $status;
    update_user_meta($user_id, 'tsp_submissions', $submissions);
    wp_send_json_success();
});

// TSP Delete Submission
add_action('wp_ajax_tsp_delete_submission', function(){
    if(!current_user_can('manage_options')) wp_send_json_error('Unauthorized');
    if(!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'tsp_admin_nonce')) wp_send_json_error('Invalid nonce');

    $user_id     = (int)($_POST['user_id']      ?? 0);
    $index       = (int)($_POST['index']        ?? -1);
    $refund_slot = ($_POST['refund_slot'] ?? 'no') === 'yes';

    if(!$user_id || $index < 0) wp_send_json_error('Invalid data');

    $submissions = get_user_meta($user_id, 'tsp_submissions', true) ?: [];
    if(!isset($submissions[$index])) wp_send_json_error('Submission not found');

    $sub = $submissions[$index];
    if(!empty($sub['audio_id'])) wp_delete_attachment($sub['audio_id'], true);
    if(!empty($sub['lyric_id'])) wp_delete_attachment($sub['lyric_id'], true);

    array_splice($submissions, $index, 1);
    update_user_meta($user_id, 'tsp_submissions', array_values($submissions));

    if($refund_slot){
        $used = (int)get_user_meta($user_id, 'tsp_slots_used', true);
        update_user_meta($user_id, 'tsp_slots_used', max(0, $used - 1));
    }

    wp_send_json_success();
});

// TSP Update Member Slots
add_action('wp_ajax_tsp_update_slots', function(){
    if(!current_user_can('manage_options')) wp_send_json_error('Unauthorized');
    if(!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'tsp_admin_nonce')) wp_send_json_error('Invalid nonce');

    $user_id     = (int)($_POST['user_id']     ?? 0);
    $slots_used  = (int)($_POST['slots_used']  ?? 0);
    $addon_slots = (int)($_POST['addon_slots'] ?? 0);

    if(!$user_id) wp_send_json_error('Invalid user');

    update_user_meta($user_id, 'tsp_slots_used',  max(0, $slots_used));
    update_user_meta($user_id, 'tsp_addon_slots', max(0, $addon_slots));
    wp_send_json_success();
});

// TSP — track membership expiry (Current vs Past Members)
add_action('pmpro_after_change_membership_level', function($level_id, $user_id){
    if(empty($user_id)) return;
    if((int)$level_id === 0){
        // Membership ended (cancelled, expired, or removed by admin).
        // Only set the clock once — don't reset it if it's already ticking.
        if(!get_user_meta($user_id, 'tsp_expired_date', true)){
            update_user_meta($user_id, 'tsp_expired_date', current_time('timestamp'));
        }
    } else {
        // Reactivated — back to Current Members, cancel any pending audio purge.
        delete_user_meta($user_id, 'tsp_expired_date');
        delete_user_meta($user_id, 'tsp_audio_purged');
        delete_user_meta($user_id, 'tsp_autorenew_cancelled');
    }
}, 10, 2);

function tsp_is_current_member($user_id){
    $level = pmpro_getMembershipLevelForUser($user_id);
    return !empty($level) && !empty($level->ID);
}

// TSP — daily cron: purge audio files 30 days after a membership actually ends.
// Lyric sheets, notes, and all other submission data are kept indefinitely.
if(!wp_next_scheduled('tsp_purge_expired_audio_event')){
    wp_schedule_event(time(), 'daily', 'tsp_purge_expired_audio_event');
}
add_action('tsp_purge_expired_audio_event', function(){
    $users = get_users(['meta_key' => 'tsp_expired_date']);
    foreach($users as $u){
        if(get_user_meta($u->ID, 'tsp_audio_purged', true) === '1') continue;

        $expired_ts = (int)get_user_meta($u->ID, 'tsp_expired_date', true);
        if(!$expired_ts) continue;
        if((current_time('timestamp') - $expired_ts) < 30 * DAY_IN_SECONDS) continue;

        $submissions = get_user_meta($u->ID, 'tsp_submissions', true) ?: [];
        $changed = false;
        foreach($submissions as $i => $sub){
            if(!empty($sub['audio_id'])){
                wp_delete_attachment($sub['audio_id'], true);
            }
            if(!empty($sub['audio_url']) || !empty($sub['audio_id'])){
                $submissions[$i]['audio_url'] = '';
                $submissions[$i]['audio_id']  = 0;
                $changed = true;
            }
        }
        if($changed){
            update_user_meta($u->ID, 'tsp_submissions', $submissions);
        }
        update_user_meta($u->ID, 'tsp_audio_purged', '1');
    }
});

// TSP Admin Menu
add_action('admin_menu', function(){
    add_menu_page(
        'TSP Submissions',
        'TSP Submissions',
        'manage_options',
        'tsp-submissions',
        'tsp_render_admin_page',
        'dashicons-music',
        30
    );
});

function tsp_render_admin_page(){
    $nonce      = wp_create_nonce('tsp_admin_nonce');
    $active_tab = $_GET['tab'] ?? 'submissions';

    $sub_users = get_users(['meta_key' => 'tsp_submissions']);
    $all_users = get_users(['role__in' => ['subscriber','administrator'], 'orderby' => 'display_name']);

    // Split every submission by whether its owner is currently a member
    $current_subs = [];
    $past_subs    = [];
    foreach($sub_users as $u){
        $is_current = tsp_is_current_member($u->ID);
        $subs = get_user_meta($u->ID, 'tsp_submissions', true) ?: [];
        foreach($subs as $i => $s){
            $row = array_merge($s, [
                'user_id'      => $u->ID,
                'display_name' => $u->display_name,
                'email'        => $u->user_email,
                'index'        => $i,
            ]);
            if($is_current) $current_subs[] = $row;
            else $past_subs[] = $row;
        }
    }
    usort($current_subs, fn($a,$b) => strtotime($b['date']) - strtotime($a['date']));
    usort($past_subs,    fn($a,$b) => strtotime($b['date']) - strtotime($a['date']));

    // Current members only, for the Manage Member Slots tab
    $current_users = array_values(array_filter($all_users, fn($u) => tsp_is_current_member($u->ID)));

    // Past members: anyone whose membership has ended, regardless of whether they have submissions
    $past_users = array_values(array_filter($all_users, fn($u) => !tsp_is_current_member($u->ID) && get_user_meta($u->ID, 'tsp_expired_date', true)));
    ?>
    <div class="wrap">
      <h1 style="margin-bottom:16px">TSP Submissions</h1>
      <nav class="nav-tab-wrapper" style="margin-bottom:24px">
        <a href="?page=tsp-submissions&tab=submissions" class="nav-tab <?php echo $active_tab==='submissions'?'nav-tab-active':''; ?>">
          Submissions <span style="background:#e0e0e0;border-radius:10px;padding:1px 8px;font-size:12px;margin-left:4px"><?php echo count($current_subs); ?></span>
        </a>
        <a href="?page=tsp-submissions&tab=past" class="nav-tab <?php echo $active_tab==='past'?'nav-tab-active':''; ?>">
          Past Members <span style="background:#e0e0e0;border-radius:10px;padding:1px 8px;font-size:12px;margin-left:4px"><?php echo count($past_users); ?></span>
        </a>
        <a href="?page=tsp-submissions&tab=slots" class="nav-tab <?php echo $active_tab==='slots'?'nav-tab-active':''; ?>">
          Manage Member Slots
        </a>
      </nav>

      <?php if($active_tab === 'submissions'): ?>
      <p style="color:#666;margin-bottom:20px">Active members only. When a membership ends, that member and their submissions move to the Past Members tab.</p>
      <table class="wp-list-table widefat fixed striped" style="border-radius:8px;overflow:hidden">
        <thead>
          <tr>
            <th style="width:150px">Song Title</th>
            <th style="width:160px">Songwriter</th>
            <th style="width:80px">Genre</th>
            <th style="width:150px">Member</th>
            <th style="width:90px">Date</th>
            <th style="width:185px">Audio</th>
            <th style="width:70px">Lyrics</th>
            <th style="width:145px">Status</th>
            <th style="width:90px">Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php if(empty($current_subs)): ?>
          <tr><td colspan="9" style="text-align:center;padding:40px;color:#999">No submissions yet.</td></tr>
          <?php else: ?>
          <?php foreach($current_subs as $s): ?>
          <tr id="tsp-row-<?php echo $s['user_id'].'-'.$s['index']; ?>">
            <td>
              <strong><?php echo esc_html($s['song_title']); ?></strong>
              <?php if(!empty($s['notes'])): ?>
              <br><span style="font-size:11px;color:#999" title="<?php echo esc_attr($s['notes']); ?>">Has notes &#9432;</span>
              <?php endif; ?>
            </td>
            <td>
              <?php echo esc_html($s['artist']); ?>
              <?php if(!empty($s['pro']) || !empty($s['ownership_pct'])): ?>
              <br><span style="font-size:11px;color:#999"><?php echo esc_html($s['pro'] ?? ''); ?><?php if(!empty($s['ownership_pct'])): ?> &middot; <?php echo esc_html($s['ownership_pct']); ?>%<?php endif; ?></span>
              <?php endif; ?>
              <?php if(!empty($s['cowriters'])): ?>
              <br><span style="font-size:11px;color:#999">Co: <?php echo esc_html($s['cowriters']); ?></span>
              <?php endif; ?>
            </td>
            <td><?php echo esc_html($s['genre']); ?></td>
            <td>
              <?php echo esc_html($s['display_name']); ?>
              <br><span style="font-size:11px;color:#999"><?php echo esc_html($s['email']); ?></span>
            </td>
            <td style="font-size:12px;color:#666"><?php echo date('M j, Y', strtotime($s['date'])); ?></td>
            <td>
              <?php if(!empty($s['audio_url'])): ?>
              <audio controls style="width:100%;max-width:175px;height:32px">
                <source src="<?php echo esc_url($s['audio_url']); ?>">
              </audio>
              <?php else: ?>
              <span style="font-size:12px;color:#bbb">No file</span>
              <?php endif; ?>
            </td>
            <td>
              <?php if(!empty($s['lyric_url'])): ?>
              <a href="<?php echo esc_url($s['lyric_url']); ?>" target="_blank" style="font-size:12px;color:#2271b1;text-decoration:underline">View</a>
              <?php else: ?>
              <span style="font-size:12px;color:#bbb">None</span>
              <?php endif; ?>
            </td>
            <td>
              <?php
              $status = $s['status'] ?? 'pending';
              $colors = ['pending'=>'#f59e0b','reviewed'=>'#3b82f6','pitched'=>'#8b5cf6','placed'=>'#10b981'];
              $color  = $colors[$status] ?? '#999';
              ?>
              <select
                data-user="<?php echo $s['user_id']; ?>"
                data-index="<?php echo $s['index']; ?>"
                data-nonce="<?php echo $nonce; ?>"
                onchange="tspUpdateStatus(this)"
                style="border:2px solid <?php echo $color; ?>;border-radius:4px;padding:4px 6px;font-weight:600;color:<?php echo $color; ?>;background:#fff;cursor:pointer;width:100%"
              >
                <option value="pending"  <?php selected($status,'pending');  ?>>Pending</option>
                <option value="reviewed" <?php selected($status,'reviewed'); ?>>Reviewed</option>
                <option value="pitched"  <?php selected($status,'pitched');  ?>>Pitched</option>
                <option value="placed"   <?php selected($status,'placed');   ?>>Placed</option>
              </select>
              <span class="tsp-status-msg" style="font-size:11px;color:#10b981;display:none;margin-top:2px">Saved ✓</span>
            </td>
            <td>
              <button
                onclick="tspDeleteSubmission(this)"
                data-user="<?php echo $s['user_id']; ?>"
                data-index="<?php echo $s['index']; ?>"
                data-title="<?php echo esc_attr($s['song_title']); ?>"
                data-nonce="<?php echo $nonce; ?>"
                style="background:#ef4444;color:#fff;border:none;border-radius:4px;padding:5px 10px;cursor:pointer;font-size:12px;font-weight:600"
              >Delete</button>
            </td>
          </tr>
          <?php endforeach; ?>
          <?php endif; ?>
        </tbody>
      </table>

      <?php elseif($active_tab === 'past'): ?>
      <p style="color:#666;margin-bottom:20px">Members whose subscription has ended. Audio files are automatically removed 30 days after expiry to save storage — lyric sheets, notes, and all other submission data are kept. If a member rejoins, they move back to the Submissions tab automatically.</p>

      <h2 style="font-size:16px;margin:0 0 12px">Past Members</h2>
      <table class="wp-list-table widefat fixed striped" style="border-radius:8px;overflow:hidden;margin-bottom:36px">
        <thead>
          <tr>
            <th style="width:220px">Member</th>
            <th style="width:140px">Membership Ended</th>
            <th style="width:200px">Audio Files</th>
            <th style="width:120px">Submissions</th>
          </tr>
        </thead>
        <tbody>
          <?php if(empty($past_users)): ?>
          <tr><td colspan="4" style="text-align:center;padding:40px;color:#999">No past members yet.</td></tr>
          <?php else: ?>
          <?php foreach($past_users as $u):
              $expired_ts   = (int)get_user_meta($u->ID, 'tsp_expired_date', true);
              $purged       = get_user_meta($u->ID, 'tsp_audio_purged', true) === '1';
              $days_left    = $purged ? 0 : max(0, 30 - floor((current_time('timestamp') - $expired_ts) / DAY_IN_SECONDS));
              $sub_count    = count(get_user_meta($u->ID, 'tsp_submissions', true) ?: []);
          ?>
          <tr>
            <td>
              <strong><?php echo esc_html($u->display_name); ?></strong>
              <br><span style="font-size:11px;color:#999"><?php echo esc_html($u->user_email); ?></span>
            </td>
            <td style="font-size:12px;color:#666"><?php echo $expired_ts ? date('M j, Y', $expired_ts) : '—'; ?></td>
            <td>
              <?php if($purged): ?>
              <span style="font-size:12px;color:#999">Removed</span>
              <?php else: ?>
              <span style="font-size:12px;color:#d97706">Removes in <?php echo esc_html($days_left); ?> day<?php echo $days_left==1?'':'s'; ?></span>
              <?php endif; ?>
            </td>
            <td style="font-size:12px;color:#666"><?php echo $sub_count; ?> submission<?php echo $sub_count==1?'':'s'; ?></td>
          </tr>
          <?php endforeach; ?>
          <?php endif; ?>
        </tbody>
      </table>

      <h2 style="font-size:16px;margin:0 0 12px">Past Member Submissions</h2>
      <table class="wp-list-table widefat fixed striped" style="border-radius:8px;overflow:hidden">
        <thead>
          <tr>
            <th style="width:170px">Song Title</th>
            <th style="width:170px">Songwriter</th>
            <th style="width:90px">Genre</th>
            <th style="width:170px">Member</th>
            <th style="width:100px">Date</th>
            <th style="width:130px">Audio</th>
            <th style="width:80px">Lyrics</th>
            <th style="width:110px">Status</th>
          </tr>
        </thead>
        <tbody>
          <?php if(empty($past_subs)): ?>
          <tr><td colspan="8" style="text-align:center;padding:40px;color:#999">No submissions from past members.</td></tr>
          <?php else: ?>
          <?php foreach($past_subs as $s):
              $status = $s['status'] ?? 'pending';
              $colors = ['pending'=>'#f59e0b','reviewed'=>'#3b82f6','pitched'=>'#8b5cf6','placed'=>'#10b981'];
              $color  = $colors[$status] ?? '#999';
          ?>
          <tr>
            <td><strong><?php echo esc_html($s['song_title']); ?></strong></td>
            <td>
              <?php echo esc_html($s['artist']); ?>
              <?php if(!empty($s['cowriters'])): ?>
              <br><span style="font-size:11px;color:#999">Co: <?php echo esc_html($s['cowriters']); ?></span>
              <?php endif; ?>
            </td>
            <td><?php echo esc_html($s['genre']); ?></td>
            <td>
              <?php echo esc_html($s['display_name']); ?>
              <br><span style="font-size:11px;color:#999"><?php echo esc_html($s['email']); ?></span>
            </td>
            <td style="font-size:12px;color:#666"><?php echo date('M j, Y', strtotime($s['date'])); ?></td>
            <td>
              <?php if(!empty($s['audio_url'])): ?>
              <audio controls style="width:100%;max-width:120px;height:32px">
                <source src="<?php echo esc_url($s['audio_url']); ?>">
              </audio>
              <?php else: ?>
              <span style="font-size:12px;color:#bbb">Removed</span>
              <?php endif; ?>
            </td>
            <td>
              <?php if(!empty($s['lyric_url'])): ?>
              <a href="<?php echo esc_url($s['lyric_url']); ?>" target="_blank" style="font-size:12px;color:#2271b1;text-decoration:underline">View</a>
              <?php else: ?>
              <span style="font-size:12px;color:#bbb">None</span>
              <?php endif; ?>
            </td>
            <td>
              <span style="color:<?php echo $color; ?>;font-weight:600;font-size:12px"><?php echo ucfirst($status); ?></span>
            </td>
          </tr>
          <?php endforeach; ?>
          <?php endif; ?>
        </tbody>
      </table>

      <?php elseif($active_tab === 'slots'): ?>
      <p style="color:#666;margin-bottom:20px">Manually adjust submission slots for current members. Changes take effect immediately.</p>
      <table class="wp-list-table widefat fixed striped" style="border-radius:8px;overflow:hidden">
        <thead>
          <tr>
            <th style="width:200px">Member</th>
            <th style="width:120px">Tier</th>
            <th style="width:120px">Slots Used</th>
            <th style="width:120px">Add-on Slots</th>
            <th style="width:120px">Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php
          $tC = [1=>'Bronze',2=>'Silver',3=>'Gold',4=>'Platinum'];
          if(empty($current_users)): ?>
          <tr><td colspan="5" style="text-align:center;padding:40px;color:#999">No current members.</td></tr>
          <?php else: foreach($current_users as $u):
              $level       = pmpro_getMembershipLevelForUser($u->ID);
              $level_id    = $level ? (int)$level->id : null;
              $tier_label  = $level_id ? ($tC[$level_id] ?? 'Unknown') : 'No membership';
              $slots_used  = (int)get_user_meta($u->ID, 'tsp_slots_used',  true);
              $addon_slots = (int)get_user_meta($u->ID, 'tsp_addon_slots', true);
          ?>
          <tr>
            <td>
              <strong><?php echo esc_html($u->display_name); ?></strong>
              <br><span style="font-size:11px;color:#999"><?php echo esc_html($u->user_email); ?></span>
            </td>
            <td><?php echo esc_html($tier_label); ?></td>
            <td>
              <input type="number" id="slots-used-<?php echo $u->ID; ?>" value="<?php echo $slots_used; ?>" min="0"
                style="width:70px;padding:4px 6px;border:1px solid #ddd;border-radius:4px" />
            </td>
            <td>
              <input type="number" id="addon-slots-<?php echo $u->ID; ?>" value="<?php echo $addon_slots; ?>" min="0"
                style="width:70px;padding:4px 6px;border:1px solid #ddd;border-radius:4px" />
            </td>
            <td>
              <button onclick="tspUpdateSlots(<?php echo $u->ID; ?>,'<?php echo $nonce; ?>')"
                style="background:#2271b1;color:#fff;border:none;border-radius:4px;padding:5px 12px;cursor:pointer;font-size:12px;font-weight:600">Save</button>
              <span id="slots-msg-<?php echo $u->ID; ?>" style="font-size:11px;color:#10b981;display:none;margin-left:6px">Saved ✓</span>
            </td>
          </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
      <?php endif; ?>
    </div>

    <!-- Delete Modal -->
    <div id="tsp-delete-modal" style="display:none;position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.6);z-index:99999;align-items:center;justify-content:center">
      <div style="background:#fff;border-radius:10px;padding:32px;max-width:420px;width:90%;box-shadow:0 20px 60px rgba(0,0,0,0.3)">
        <h3 style="margin:0 0 8px;font-size:18px">Delete Submission</h3>
        <p id="tsp-delete-title" style="color:#666;margin:0 0 24px;font-size:14px"></p>
        <p style="font-size:13px;font-weight:600;margin:0 0 12px">What would you like to do with the submission slot?</p>
        <div style="display:flex;flex-direction:column;gap:10px;margin-bottom:24px">
          <button onclick="tspConfirmDelete('yes')" style="background:#ef4444;color:#fff;border:none;border-radius:6px;padding:11px 16px;cursor:pointer;font-size:14px;font-weight:600;text-align:left">
            🗑 Delete &amp; Restore Slot — member gets the slot back
          </button>
          <button onclick="tspConfirmDelete('no')" style="background:#6b7280;color:#fff;border:none;border-radius:6px;padding:11px 16px;cursor:pointer;font-size:14px;font-weight:600;text-align:left">
            🗑 Delete Only — slot count unchanged
          </button>
        </div>
        <button onclick="tspCloseDeleteModal()" style="background:none;border:1px solid #ddd;border-radius:6px;padding:8px 20px;cursor:pointer;font-size:13px;color:#666">Cancel</button>
      </div>
    </div>

    <script>
    var tspPendingDelete = null;

    function tspUpdateStatus(sel){
      var uid=sel.dataset.user,idx=sel.dataset.index,nonce=sel.dataset.nonce,status=sel.value;
      var colors={pending:'#f59e0b',reviewed:'#3b82f6',pitched:'#8b5cf6',placed:'#10b981'};
      sel.style.borderColor=colors[status];sel.style.color=colors[status];
      var msg=sel.parentNode.querySelector('.tsp-status-msg');
      var fd=new FormData();
      fd.append('action','tsp_update_status');fd.append('nonce',nonce);
      fd.append('user_id',uid);fd.append('index',idx);fd.append('status',status);
      fetch('<?php echo admin_url('admin-ajax.php'); ?>',{method:'POST',credentials:'include',body:fd})
        .then(function(r){return r.json();})
        .then(function(res){
          if(res.success){msg.style.display='inline';setTimeout(function(){msg.style.display='none';},2000);}
          else{alert('Failed to update status.');}
        });
    }

    function tspDeleteSubmission(btn){
      tspPendingDelete={user:btn.dataset.user,index:btn.dataset.index,nonce:btn.dataset.nonce,rowId:'tsp-row-'+btn.dataset.user+'-'+btn.dataset.index};
      document.getElementById('tsp-delete-title').textContent='Deleting: "'+btn.dataset.title+'"';
      document.getElementById('tsp-delete-modal').style.display='flex';
    }

    function tspCloseDeleteModal(){
      document.getElementById('tsp-delete-modal').style.display='none';
      tspPendingDelete=null;
    }

    function tspConfirmDelete(refund){
      if(!tspPendingDelete) return;
      var d=tspPendingDelete;
      var fd=new FormData();
      fd.append('action','tsp_delete_submission');fd.append('nonce',d.nonce);
      fd.append('user_id',d.user);fd.append('index',d.index);fd.append('refund_slot',refund);
      fetch('<?php echo admin_url('admin-ajax.php'); ?>',{method:'POST',credentials:'include',body:fd})
        .then(function(r){return r.json();})
        .then(function(res){
          if(res.success){
            var row=document.getElementById(d.rowId);
            if(row){row.style.background='#fee2e2';row.style.transition='opacity 0.4s';
              setTimeout(function(){row.style.opacity='0';},100);
              setTimeout(function(){row.remove();},500);}
            tspCloseDeleteModal();
          } else {alert('Delete failed. Please try again.');}
        });
    }

    function tspUpdateSlots(userId,nonce){
      var used=document.getElementById('slots-used-'+userId).value;
      var addon=document.getElementById('addon-slots-'+userId).value;
      var msg=document.getElementById('slots-msg-'+userId);
      var fd=new FormData();
      fd.append('action','tsp_update_slots');fd.append('nonce',nonce);
      fd.append('user_id',userId);fd.append('slots_used',used);fd.append('addon_slots',addon);
      fetch('<?php echo admin_url('admin-ajax.php'); ?>',{method:'POST',credentials:'include',body:fd})
        .then(function(r){return r.json();})
        .then(function(res){
          if(res.success){msg.style.display='inline';setTimeout(function(){msg.style.display='none';},2500);}
          else{alert('Failed to update slots.');}
        });
    }
    </script>
    <?php
}


// TSP Member Dashboard
add_action('wp_footer', function(){
    if(!is_page(542)) return;
    $user = wp_get_current_user();
    if(!$user->ID) return;
    $level = pmpro_getMembershipLevelForUser($user->ID);
    $meta  = get_user_meta($user->ID);

    $tC = [
        1 => ['label'=>'Bronze',   'base'=>6,  'price'=>'$10.99', 'max'=>2,    'url'=>'https://buy.stripe.com/00w4gy7ar4lddxobnGefC00'],
        2 => ['label'=>'Silver',   'base'=>8,  'price'=>'$11.99', 'max'=>4,    'url'=>'https://buy.stripe.com/8x27sKfGX2d5gJA2RaefC01'],
        3 => ['label'=>'Gold',     'base'=>10, 'price'=>'$12.99', 'max'=>5,    'url'=>'https://buy.stripe.com/fZudR8eCT8Bt3WOajCefC02'],
        4 => ['label'=>'Platinum', 'base'=>12, 'price'=>'$14.99', 'max'=>null, 'url'=>'https://buy.stripe.com/28E9AS9izcRJfFwfDWefC03'],
    ];

    $level_id    = $level ? (int)$level->id : 1;
    $cfg         = $tC[$level_id] ?? $tC[1];
    $addon_slots = (int)($meta['tsp_addon_slots'][0] ?? 0);
    $slots_used  = (int)($meta['tsp_slots_used'][0]  ?? 0);
    $total       = $cfg['base'] + $addon_slots;
    $remaining   = max(0, $total - $slots_used);

    $data = [
        'logged_in'       => true,
        'display_name'    => $user->display_name,
        'email'           => $user->user_email,
        'level_id'        => $level_id,
        'expiry'          => $level ? $level->enddate : '',
        'addon_slots'     => $addon_slots,
        'slots_used'      => $slots_used,
        'slots_total'     => $total,
        'slots_remaining' => $remaining,
        'addon_price'     => $cfg['price'],
        'tier_label'      => $cfg['label'],
        'addon_max'       => $cfg['max'],
        'addon_url'       => $cfg['url'],
        'addon_maxed'     => $cfg['max'] !== null && $addon_slots >= $cfg['max'],
        'submissions'     => array_values(get_user_meta($user->ID, 'tsp_submissions', true) ?: []),
        'ajax_url'        => admin_url('admin-ajax.php'),
        'nonce'           => wp_create_nonce('tsp_nonce'),
    ];
    ?>
    <style>
    #tsp-submissions-table td, #tsp-submissions-table th { padding: 12px 20px !important; }
    </style>
    <script>
    window.TSP=<?php echo json_encode($data); ?>;
    (function(){
      var d=window.TSP;
      if(!d||!d.logged_in){
        var g=document.getElementById('tsp-gate');if(g)g.style.display='block';
        return;
      }
      var dash=document.getElementById('tsp-dashboard');if(dash)dash.style.display='block';
      var tn=document.getElementById('tsp-tier-name');if(tn)tn.textContent=d.tier_label;
      var tr=document.getElementById('tsp-tier-renews');if(tr&&d.expiry)tr.textContent='Renews '+d.expiry;
      var st=document.getElementById('tsp-slots-total');if(st)st.textContent=d.slots_total;
      var su=document.getElementById('tsp-slots-used');if(su)su.textContent=d.slots_used;
      var sr=document.getElementById('tsp-slots-remaining');
      if(sr){sr.textContent=d.slots_remaining;sr.style.color=d.slots_remaining>0?'#4ade80':'#f87171';}
      var un=document.getElementById('tsp-user-name');if(un)un.textContent=d.display_name;
      var ue=document.getElementById('tsp-user-email');if(ue)ue.textContent=d.email;
      var ap=document.getElementById('tsp-addon-price');if(ap)ap.textContent=d.addon_price+' / slot';
      var al=document.getElementById('tsp-addon-limit');
      if(al)al.textContent=d.addon_max===null?'Unlimited add-ons available':'Max '+d.addon_max+' add-on slot'+(d.addon_max===1?'':'s')+' for your tier';
      var bb=document.getElementById('tsp-buy-btn');if(bb&&d.addon_url)bb.href=d.addon_url;
      if(d.addon_maxed){if(bb)bb.style.display='none';var am=document.getElementById('tsp-addon-maxed');if(am)am.style.display='block';}
      var loading=document.getElementById('tsp-submissions-loading');if(loading)loading.style.display='none';
      var subs=d.submissions||[];
      if(subs.length===0){
        var ns=document.getElementById('tsp-no-submissions');if(ns)ns.style.display='block';
      } else {
        var tbl=document.getElementById('tsp-submissions-table');
        if(tbl){tbl.style.display='table';tbl.style.width='100%';}
        var tbody=document.getElementById('tsp-submissions-body');
        if(tbody){
          subs.forEach(function(s){
            var row=document.createElement('tr');
            var scMap={pending:'rgba(255,255,255,0.5)',reviewed:'#60a5fa',pitched:'#a78bfa',placed:'#4ade80'};var sc=scMap[s.status]||'rgba(255,255,255,0.5)';
            var dateStr=s.date?new Date(s.date).toLocaleDateString('en-US',{month:'short',day:'numeric',year:'numeric'}):'';
            row.innerHTML='<td>'+s.song_title+'</td><td>'+s.artist+'</td><td>'+s.genre+'</td><td>'+dateStr+'</td>'
              +'<td style="text-align:center;color:'+sc+';font-weight:600;font-size:11px;letter-spacing:.07em">'+s.status.toUpperCase()+'</td>';
            tbody.appendChild(row);
          });
        }
      }
      // Submit Songs Here button below submissions card
      var subCard=document.querySelector('.tsp-card');
      if(subCard){
        var submitBtn=document.createElement('div');
        submitBtn.style.cssText='text-align:center;padding:20px 20px 24px';
        submitBtn.innerHTML='<a href="/song-submission-portal/" style="display:inline-block;background:transparent;color:#fff;border:1px solid rgba(255,255,255,0.4);padding:12px 36px;font-size:13px;font-weight:700;letter-spacing:.08em;border-radius:6px;text-decoration:none;transition:all .2s">SUBMIT SONGS HERE \u2192</a>';
        subCard.appendChild(submitBtn);
      }
    })();
    </script>
    <?php
});

// TSP Portal Script
add_action('wp_footer', function(){
    if(!is_page(458)) return;
    $user = wp_get_current_user();
    if(!$user->ID) return;
    $level = pmpro_getMembershipLevelForUser($user->ID);
    $meta  = get_user_meta($user->ID);

    $tC = [
        1 => ['label'=>'Bronze',   'base'=>6,  'max'=>2,    'url'=>'https://buy.stripe.com/00w4gy7ar4lddxobnGefC00'],
        2 => ['label'=>'Silver',   'base'=>8,  'max'=>4,    'url'=>'https://buy.stripe.com/8x27sKfGX2d5gJA2RaefC01'],
        3 => ['label'=>'Gold',     'base'=>10, 'max'=>5,    'url'=>'https://buy.stripe.com/fZudR8eCT8Bt3WOajCefC02'],
        4 => ['label'=>'Platinum', 'base'=>12, 'max'=>null, 'url'=>'https://buy.stripe.com/28E9AS9izcRJfFwfDWefC03'],
    ];

    $level_id    = $level ? (int)$level->id : 1;
    $cfg         = $tC[$level_id] ?? $tC[1];
    $addon_slots = (int)($meta['tsp_addon_slots'][0] ?? 0);
    $slots_used  = (int)($meta['tsp_slots_used'][0]  ?? 0);
    $total       = $cfg['base'] + $addon_slots;
    $remaining   = max(0, $total - $slots_used);

    $data = [
        'logged_in'       => true,
        'user_id'         => $user->ID,
        'tier_label'      => $cfg['label'],
        'slots_used'      => $slots_used,
        'slots_total'     => $total,
        'slots_remaining' => $remaining,
        'addon_max'       => $cfg['max'],
        'addon_url'       => $cfg['url'],
        'ajax_url'        => admin_url('admin-ajax.php'),
        'nonce'           => wp_create_nonce('tsp_nonce'),
    ];
    ?>
    <script>
    window.TSP_PORTAL=<?php echo json_encode($data); ?>;
    (function(){
      var d=window.TSP_PORTAL;
      if(!d||!d.logged_in){
        var g=document.getElementById('tsp-portal-gate');if(g)g.style.display='block';
        var f=document.getElementById('song-submission-form');if(f)f.style.display='none';
        return;
      }
      var remaining=d.slots_remaining;
      var bar=document.getElementById('tsp-slot-bar');if(bar)bar.style.display='flex';
      var pt=document.getElementById('tsp-portal-tier');if(pt)pt.textContent=d.tier_label;
      var pr=document.getElementById('tsp-portal-remaining');
      if(pr){pr.textContent=remaining;pr.style.color=remaining>0?'#4ade80':'#f87171';}
      var put=document.getElementById('tsp-portal-used-total');if(put)put.textContent=d.slots_used+' / '+d.slots_total;
      function setFormDisabled(disabled){
        var f=document.getElementById('song-submission-form'),b=document.getElementById('tsp-submit-btn');
        if(!f||!b)return;
        Array.prototype.forEach.call(f.querySelectorAll('input,select,textarea,button'),function(el){el.disabled=disabled;});
        b.style.opacity=disabled?'0.4':'1';b.style.cursor=disabled?'not-allowed':'pointer';
      }
      if(remaining<=0){
        var nb=document.getElementById('tsp-no-slots-banner');if(nb)nb.style.display='block';
        var bb=document.getElementById('tsp-portal-buy-btn');if(bb&&d.addon_url)bb.href=d.addon_url;
        setFormDisabled(true);
      }
      var form=document.getElementById('song-submission-form');
      if(form){
        form.addEventListener('submit',function(e){
          e.preventDefault();
          var btn=document.getElementById('tsp-submit-btn');
          btn.textContent='Submitting...';btn.disabled=true;
          var formData=new FormData(form);
          formData.append('action','tsp_save_submission');
          formData.append('nonce',d.nonce);
          fetch(d.ajax_url,{method:'POST',credentials:'include',body:formData})
          .then(function(r){return r.json();})
          .then(function(res){
            if(res.success){
              d.slots_used=(d.slots_used||0)+1;
              remaining=Math.max(0,d.slots_total-d.slots_used);
              var ss=document.getElementById('tsp-submit-success');if(ss)ss.style.display='block';
              form.reset();
              btn.textContent='SUBMIT SONG \u2192';btn.disabled=false;
              if(pr){pr.textContent=remaining;pr.style.color=remaining>0?'#4ade80':'#f87171';}
              if(put)put.textContent=d.slots_used+' / '+d.slots_total;
              if(remaining<=0){
                var nb2=document.getElementById('tsp-no-slots-banner');if(nb2)nb2.style.display='block';
                var bb2=document.getElementById('tsp-portal-buy-btn');if(bb2&&d.addon_url)bb2.href=d.addon_url;
                setFormDisabled(true);
              }
            } else {
              alert('Submission failed. Please try again or contact info@thesongplug.com');
              btn.textContent='SUBMIT SONG \u2192';btn.disabled=false;
            }
          }).catch(function(){
            alert('Network error. Please try again.');
            btn.textContent='SUBMIT SONG \u2192';btn.disabled=false;
          });
        });
      }
    })();
    </script>
    <?php
});


// TSP — Auto Renew Date + Cancel Auto Renew (Membership Account page, ID 516)
// Cancels future billing via Stripe's cancel_at_period_end, which leaves the
// member's access fully active until the term they already paid for ends.
// This is deliberately separate from PMPro's built-in "Cancel" link on this
// same page, which ends access immediately when clicked.

function tsp_get_active_pmpro_subscription($user_id){
    global $wpdb;
    $table = $wpdb->prefix . 'pmpro_subscriptions';
    $exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table));
    if(!$exists) return null;

    $row = $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM {$table} WHERE user_id = %d AND status = 'active' ORDER BY id DESC LIMIT 1",
        $user_id
    ));
    return $row ?: null;
}

function tsp_get_stripe_secret_key(){
    // Try PMPro's own gateway bootstrap first, so we stay in sync with
    // whichever environment (sandbox/live) PMPro is currently set to.
    if(class_exists('PMProGateway_stripe') && method_exists('PMProGateway_stripe','getGateway')){
        try {
            PMProGateway_stripe::getGateway();
            if(class_exists('\Stripe\Stripe')){
                $key = \Stripe\Stripe::getApiKey();
                if(!empty($key)) return $key;
            }
        } catch (\Throwable $e) { /* fall through to manual lookup */ }
    }

    // Fallback: read PMPro's stored Stripe key directly from its options.
    $env  = get_option('pmpro_gateway_environment', 'live');
    $keys = ['pmpro_stripe_secretkey', 'pmpro_stripe_secretkey_' . $env];
    foreach($keys as $opt){
        $val = get_option($opt);
        if(!empty($val)) return $val;
    }
    return '';
}

add_action('wp_footer', function(){
    if(!is_page(516)) return;
    $user = wp_get_current_user();
    if(!$user->ID) return;

    $level = pmpro_getMembershipLevelForUser($user->ID);
    if(!$level || empty($level->ID)) return; // no active membership — nothing to show

    $sub = tsp_get_active_pmpro_subscription($user->ID);

    $next_payment_date = '';
    $has_recurring      = false;
    if($sub && !empty($sub->next_payment_date) && $sub->next_payment_date !== '0000-00-00'){
        $ts = strtotime($sub->next_payment_date);
        if($ts){ $next_payment_date = date('F j, Y', $ts); $has_recurring = true; }
    }
    // Fallback to PMPro's own helper if the subscriptions table lookup came up empty
    if(!$has_recurring && function_exists('pmpro_next_payment')){
        $ts = pmpro_next_payment($user->ID, 'timestamp');
        if($ts){ $next_payment_date = date('F j, Y', $ts); $has_recurring = true; }
    }
    if(!$has_recurring) return; // not on a recurring plan — nothing to cancel

    $data = [
        'next_payment_date'  => $next_payment_date,
        'level_name'         => $level->name,
        'already_cancelled'  => (bool) get_user_meta($user->ID, 'tsp_autorenew_cancelled', true),
        'ajax_url'           => admin_url('admin-ajax.php'),
        'nonce'              => wp_create_nonce('tsp_account_nonce'),
    ];
    ?>
    <script>
    window.TSP_ACCOUNT = <?php echo json_encode($data); ?>;
    (function(){
      var d = window.TSP_ACCOUNT;
      var host = document.querySelector('.pmpro_account')
              || document.querySelector('#pmpro_account')
              || document.querySelector('.entry-content')
              || document.body;

      var box = document.createElement('div');
      box.id = 'tsp-autorenew-box';
      box.style.cssText = 'background:#f7f7f9;border:1px solid #e2e2e6;border-radius:8px;padding:18px 22px;margin:0 0 28px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:14px;font-family:inherit';

      if(d.already_cancelled){
        box.innerHTML =
          '<div style="width:100%;font-size:14px;color:#166534;background:#dcfce7;border:1px solid #86efac;border-radius:6px;padding:12px 16px">'
          + 'Auto-renew is cancelled. Your ' + d.level_name + ' benefits remain active through <strong>' + d.next_payment_date + '</strong>. You will not be charged again.'
          + '</div>';
      } else {
        box.innerHTML =
          '<div>'
            + '<div style="font-size:12px;letter-spacing:.06em;color:#888;text-transform:uppercase;margin-bottom:4px">Auto Renew Date</div>'
            + '<div id="tsp-autorenew-date" style="font-size:17px;font-weight:700;color:#222">' + d.next_payment_date + '</div>'
          + '</div>'
          + '<button id="tsp-cancel-autorenew-btn" style="background:#fff;border:1px solid #d33;color:#d33;padding:10px 20px;border-radius:6px;font-weight:600;font-size:13px;cursor:pointer">Cancel Auto Renew Here</button>'
          + '<div id="tsp-autorenew-msg" style="display:none;width:100%;font-size:13px;color:#166534;background:#dcfce7;border:1px solid #86efac;border-radius:6px;padding:10px 14px"></div>';
      }

      host.insertBefore(box, host.firstChild);

      var btn = document.getElementById('tsp-cancel-autorenew-btn');
      if(btn){
        btn.addEventListener('click', function(){
          if(!confirm('Cancel auto-renew for your ' + d.level_name + ' membership?\n\nYou will keep full member benefits through your current term end date (' + d.next_payment_date + '). You will not be charged again after that.')) return;
          btn.disabled = true; btn.textContent = 'Cancelling...';
          var fd = new FormData();
          fd.append('action','tsp_cancel_autorenew');
          fd.append('nonce', d.nonce);
          fetch(d.ajax_url, {method:'POST', credentials:'include', body:fd})
            .then(function(r){return r.json();})
            .then(function(res){
              if(res.success){
                btn.style.display = 'none';
                var msg = document.getElementById('tsp-autorenew-msg');
                msg.style.display = 'block';
                msg.textContent = 'Auto-renew cancelled. Your ' + d.level_name + ' benefits remain active through ' + d.next_payment_date + '. You will not be charged again.';
              } else {
                alert((res.data || 'Something went wrong.') + ' Please contact info@thesongplug.com and we\'ll take care of it.');
                btn.disabled = false; btn.textContent = 'Cancel Auto Renew Here';
              }
            }).catch(function(){
              alert('Network error. Please contact info@thesongplug.com and we\'ll take care of it.');
              btn.disabled = false; btn.textContent = 'Cancel Auto Renew Here';
            });
        });
      }
    })();
    </script>
    <?php
});

add_action('wp_ajax_tsp_cancel_autorenew', function(){
    if(!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'tsp_account_nonce')){
        wp_send_json_error('Security check failed — please refresh the page and try again.');
    }
    $user = wp_get_current_user();
    if(!$user->ID) wp_send_json_error('Not logged in.');

    $sub = tsp_get_active_pmpro_subscription($user->ID);
    if(!$sub || empty($sub->subscription_transaction_id)){
        wp_send_json_error('We could not find an active subscription on your account.');
    }

    $secret_key = tsp_get_stripe_secret_key();
    if(empty($secret_key) || !class_exists('\Stripe\Subscription')){
        error_log('TSP cancel_autorenew: no Stripe key/SDK available for user '.$user->ID);
        wp_send_json_error('Auto-renew cancellation is temporarily unavailable.');
    }

    try {
        \Stripe\Stripe::setApiKey($secret_key);
        \Stripe\Subscription::update($sub->subscription_transaction_id, [
            'cancel_at_period_end' => true,
        ]);
    } catch (\Throwable $e) {
        error_log('TSP cancel_autorenew failed for user '.$user->ID.': '.$e->getMessage());
        wp_send_json_error('We could not process the cancellation.');
    }

    update_user_meta($user->ID, 'tsp_autorenew_cancelled', current_time('timestamp'));
    wp_send_json_success();
});

// Redirect after login to member dashboard
add_filter('login_redirect', function($redirect_to, $requested_redirect_to, $user){
    if($user && !is_wp_error($user) && in_array('subscriber', (array)$user->roles)){
        return home_url('/member-dashboard/');
    }
    return $redirect_to;
}, 10, 3);

// TSP Stripe Webhook — Add-on Slot Purchases
add_action('wp_ajax_nopriv_tsp_stripe_webhook', 'tsp_handle_stripe_webhook');
add_action('wp_ajax_tsp_stripe_webhook', 'tsp_handle_stripe_webhook');

function tsp_handle_stripe_webhook(){
    $sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '';
    $payload    = file_get_contents('php://input');
    $secret     = 'whsec_OMpS4N7bJnhBrUedrW4fgKqnVf5VGGdl';

    $price_map = [
        'price_1ThCe8BGtkn5uaUuHCw16LFG' => 'Bronze',
        'price_1ThCeBBGtkn5uaUugFdsibNA' => 'Silver',
        'price_1ThCeEBGtkn5uaUumrGUZZxc' => 'Gold',
        'price_1ThCeGBGtkn5uaUuRBGFWcWz' => 'Platinum',
    ];

    $event = tsp_stripe_verify($payload, $sig_header, $secret);
    if(is_wp_error($event)){
        wp_send_json(['error' => $event->get_error_message()], 400);
    }

    if($event['type'] !== 'checkout.session.completed'){
        wp_send_json(['ignored' => true], 200);
    }

    $session  = $event['data']['object'];
    $email    = $session['customer_details']['email'] ?? $session['customer_email'] ?? '';
    $price_id = $session['metadata']['price_id'] ?? '';
    $qty      = 1;

    if(empty($email) || !isset($price_map[$price_id])){
        wp_send_json(['skipped' => 'no matching price or email'], 200);
    }

    $user = get_user_by('email', $email);
    if(!$user){
        wp_send_json(['skipped' => 'user not found'], 200);
    }

    $current = (int)get_user_meta($user->ID, 'tsp_addon_slots', true);
    update_user_meta($user->ID, 'tsp_addon_slots', $current + $qty);
    wp_send_json(['success' => true, 'addon_slots' => $current + $qty], 200);
}

function tsp_stripe_verify($payload, $sig_header, $secret){
    if(empty($sig_header)){
        return new WP_Error('no_sig', 'No Stripe signature');
    }
    $parts = explode(',', $sig_header);
    $ts    = null;
    $sigs  = [];
    foreach($parts as $part){
        [$k, $v] = explode('=', $part, 2);
        if($k === 't') $ts = $v;
        if($k === 'v1') $sigs[] = $v;
    }
    if(!$ts || empty($sigs)){
        return new WP_Error('bad_sig', 'Invalid signature format');
    }
    $signed   = $ts.'.'.$payload;
    $expected = hash_hmac('sha256', $signed, $secret);
    $valid    = false;
    foreach($sigs as $sig){
        if(hash_equals($expected, $sig)){ $valid = true; break; }
    }
    if(!$valid){
        return new WP_Error('sig_mismatch', 'Signature verification failed');
    }
    if(abs(time() - (int)$ts) > 300){
        return new WP_Error('expired', 'Webhook timestamp too old');
    }
    return json_decode($payload, true);
}

// TSP — restore PMPro Terms of Service checkbox at checkout
add_action('admin_init', function(){
    if(get_option('tsp_tos_restored') !== '1'){
        update_option('pmpro_tospage', 525);
        update_option('tsp_tos_restored', '1');
    }
});