<?php
if (!defined('ABSPATH')) exit;

// =============================================================================
// TABELA PRE-SAVE
// =============================================================================
add_action('plugins_loaded', 'imz_migrate_presave_table');
function imz_migrate_presave_table() {
    global $wpdb; $t = $wpdb->prefix.'imz_presave_subscribers'; $ch = $wpdb->get_charset_collate();
    if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $t)) !== $t) {
        require_once ABSPATH.'wp-admin/includes/upgrade.php';
        dbDelta("CREATE TABLE $t (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            post_id bigint(20) NOT NULL,
            notify_method varchar(20) NOT NULL DEFAULT 'email',
            contact varchar(255) NOT NULL,
            subscribed_at datetime NOT NULL,
            notified tinyint(1) DEFAULT 0,
            PRIMARY KEY (id),
            KEY post_id (post_id),
            UNIQUE KEY unique_sub (post_id, contact)
        ) $ch;");
    }
}

// =============================================================================
// VERIFICAR SE POST ESTÁ EM MODO PRE-SAVE
// =============================================================================
function imz_check_presave_mode($post_id) {
    // Verificar se o modo Pre-Save está ativado
    $enabled = get_post_meta($post_id, '_imz_presave_enabled', true);
    if ($enabled !== 'yes') return false;

    $release = get_post_meta($post_id, '_imz_presave_date', true);
    if (empty($release)) return false;

    // Converter data (formato Y-m-d ou d/m/Y)
    $release_ts = false;
    if (preg_match('/^\d{2}\/\d{2}\/\d{4}$/', $release)) {
        $parts = explode('/', $release);
        $release_ts = mktime(0, 0, 0, $parts[1], $parts[0], $parts[2]);
    } else {
        $release_ts = strtotime($release);
    }

    if (!$release_ts || $release_ts <= time()) {
        // Data já passou — desativar Pre-Save automaticamente
        update_post_meta($post_id, '_imz_presave_enabled', '');
        return false;
    }

    $music_title = wp_strip_all_tags(get_the_title($post_id));
    $release_date_formatted = date_i18n('d \d\e F \d\e Y', $release_ts);
    $release_iso = date('Y-m-d\TH:i:s', $release_ts);
    $thumb_url = get_the_post_thumbnail_url($post_id, 'large');
    $nonce = wp_create_nonce('imz_presave_nonce');

    $thumb_html = '';
    if ($thumb_url) {
        $thumb_html = '<div style="margin-bottom:20px;"><img src="'.esc_url($thumb_url).'" alt="'.esc_attr($music_title).'" style="width:100%;max-width:280px;border-radius:12px;border:1px solid #2a2a2a;display:block;margin:0 auto;"></div>';
    }

    return '
    <div class="imz-presave-box">
        '.$thumb_html.'
        <h2>'.esc_html($music_title).'</h2>
        <p class="imz-presave-subtitle">Lançamento previsto para <strong>'.$release_date_formatted.'</strong></p>

        <div class="imz-presave-countdown" data-release="'.$release_iso.'">
            <div class="imz-cd-unit"><span class="imz-cd-num" data-cd="days">--</span><span class="imz-cd-label">Dias</span></div>
            <div class="imz-cd-unit"><span class="imz-cd-num" data-cd="hours">--</span><span class="imz-cd-label">Horas</span></div>
            <div class="imz-cd-unit"><span class="imz-cd-num" data-cd="minutes">--</span><span class="imz-cd-label">Min</span></div>
            <div class="imz-cd-unit"><span class="imz-cd-num" data-cd="seconds">--</span><span class="imz-cd-label">Seg</span></div>
        </div>

        <div class="imz-presave-form">
            <p style="color:#888;font-size:13px;margin:0 0 12px;">Quero ser notificado quando for lançado via:</p>
            <div class="imz-presave-method">
                <button type="button" class="imz-presave-method-btn active" data-method="email"><span class="imz-method-ico">&#9993;</span>Email</button>
                <button type="button" class="imz-presave-method-btn" data-method="whatsapp"><span class="imz-method-ico">&#128242;</span>WhatsApp</button>
            </div>
            <form id="imz-presave-form">
                <input type="hidden" name="post_id" value="'.esc_attr($post_id).'">
                <input type="hidden" name="notify_method" value="email" id="imz-presave-method-input">
                <input type="hidden" name="nonce" value="'.$nonce.'">
                <div id="imz-presave-email-field">
                    <input type="email" name="contact" placeholder="O seu email" required style="margin-bottom:10px;">
                </div>
                <div id="imz-presave-whatsapp-field" style="display:none;">
                    <input type="tel" name="contact_whatsapp" placeholder="Número WhatsApp (ex: +258 84...)" style="margin-bottom:10px;">
                </div>
                <div id="imz-presave-recaptcha-wrap" style="display:flex;justify-content:center;margin-bottom:10px;"></div>
                <button type="submit" class="imz-botao-principal" style="width:100%;">Notificar-me no Lançamento</button>
            </form>
            <div id="imz-presave-messages"></div>
        </div>
    </div>

    <script>
    (function(){
        // Countdown
        var cd = document.querySelector(".imz-presave-countdown");
        if (cd) {
            var release = new Date(cd.getAttribute("data-release")).getTime();
            var timer = setInterval(function(){
                var now = new Date().getTime();
                var diff = release - now;
                if (diff <= 0) { clearInterval(timer); location.reload(); return; }
                var d = Math.floor(diff / 86400000);
                var h = Math.floor((diff % 86400000) / 3600000);
                var m = Math.floor((diff % 3600000) / 60000);
                var s = Math.floor((diff % 60000) / 1000);
                cd.querySelector("[data-cd=days]").textContent = d;
                cd.querySelector("[data-cd=hours]").textContent = h;
                cd.querySelector("[data-cd=minutes]").textContent = m;
                cd.querySelector("[data-cd=seconds]").textContent = s;
            }, 1000);
        }

        // Method toggle
        var btns = document.querySelectorAll(".imz-presave-method-btn");
        var emailField = document.getElementById("imz-presave-email-field");
        var waField = document.getElementById("imz-presave-whatsapp-field");
        var methodInput = document.getElementById("imz-presave-method-input");
        btns.forEach(function(btn){
            btn.addEventListener("click", function(){
                btns.forEach(function(b){b.classList.remove("active");});
                btn.classList.add("active");
                var method = btn.getAttribute("data-method");
                methodInput.value = method;
                if (method === "email") {
                    emailField.style.display = "block"; waField.style.display = "none";
                    emailField.querySelector("input").required = true;
                    waField.querySelector("input").required = false;
                } else {
                    emailField.style.display = "none"; waField.style.display = "block";
                    emailField.querySelector("input").required = false;
                    waField.querySelector("input").required = true;
                }
            });
        });

        // Submit
        var form = document.getElementById("imz-presave-form");
        var msg = document.getElementById("imz-presave-messages");

        // reCAPTCHA
        var presaveRcId = null;
        var presaveRcRendered = false;
        function renderPresaveRC() {
            var wrap = document.getElementById("imz-presave-recaptcha-wrap");
            var key = (typeof imz_report_ajax_data !== "undefined" && imz_report_ajax_data.recaptcha_site_key) ? imz_report_ajax_data.recaptcha_site_key : null;
            if (!wrap || !key || presaveRcRendered) return;
            if (typeof grecaptcha !== "undefined" && grecaptcha && grecaptcha.render) {
                try {
                    var rcDiv = document.createElement("div");
                    rcDiv.id = "imz-presave-recaptcha";
                    wrap.appendChild(rcDiv);
                    presaveRcId = grecaptcha.render("imz-presave-recaptcha", { sitekey: key });
                    presaveRcRendered = true;
                } catch(e) {}
            }
        }
        // Tentar renderizar agora ou esperar a API carregar
        renderPresaveRC();
        if (!presaveRcRendered) {
            var rcCheck = setInterval(function() {
                if (typeof grecaptcha !== "undefined" && grecaptcha && grecaptcha.render) {
                    clearInterval(rcCheck);
                    renderPresaveRC();
                }
            }, 500);
        }

        if (form) {
            form.addEventListener("submit", function(e){
                e.preventDefault();
                var btn = form.querySelector("button[type=submit]");
                if (btn) btn.disabled = true;
                msg.innerHTML = "";

                // Validar reCAPTCHA
                if (presaveRcId !== null && typeof grecaptcha !== "undefined") {
                    var rcResp = grecaptcha.getResponse(presaveRcId);
                    if (!rcResp) {
                        msg.innerHTML = \'<p class="imz-message imz-message-error">Por favor, complete a verificação "Não sou um robô".</p>\';
                        if (btn) btn.disabled = false;
                        return;
                    }
                }

                var fd = new FormData(form);
                fd.append("action", "imz_presave_subscribe");
                // Adicionar resposta reCAPTCHA
                if (presaveRcId !== null && typeof grecaptcha !== "undefined") {
                    fd.append("g-recaptcha-response", grecaptcha.getResponse(presaveRcId));
                }
                // Use whatsapp field if method is whatsapp
                if (methodInput.value === "whatsapp") {
                    fd.set("contact", waField.querySelector("input").value);
                }
                fetch("'.admin_url('admin-ajax.php').'", { method: "POST", body: new URLSearchParams(fd) })
                .then(function(r){return r.json();})
                .then(function(res){
                    if (presaveRcId !== null && typeof grecaptcha !== "undefined") try { grecaptcha.reset(presaveRcId); } catch(e) {}
                    if (res.success) { form.style.display = "none"; msg.innerHTML = \'<div class="imz-presave-success">\' + res.data.message + \'</div>\'; }
                    else { throw new Error(res.data.message || "Erro."); }
                })
                .catch(function(err){
                    if (presaveRcId !== null && typeof grecaptcha !== "undefined") try { grecaptcha.reset(presaveRcId); } catch(e) {}
                    msg.innerHTML = \'<p class="imz-message imz-message-error">\' + err.message + \'</p>\'; if(btn)btn.disabled=false;
                });
            });
        }
    })();
    </script>';
}

// =============================================================================
// AJAX — SUBSCREVER PRE-SAVE
// =============================================================================
add_action('wp_ajax_imz_presave_subscribe', 'imz_handle_presave_subscribe');
add_action('wp_ajax_nopriv_imz_presave_subscribe', 'imz_handle_presave_subscribe');
function imz_handle_presave_subscribe() {
    check_ajax_referer('imz_presave_nonce', 'nonce');

    // reCAPTCHA
    $rc = isset($_POST['g-recaptcha-response']) ? sanitize_text_field($_POST['g-recaptcha-response']) : '';
    if (function_exists('imz_verify_recaptcha') && !imz_verify_recaptcha($rc)) {
        wp_send_json_error(['message' => 'Por favor, complete a verificação "Não sou um robô".']);
    }

    $post_id = absint($_POST['post_id'] ?? 0);
    $method = sanitize_key($_POST['notify_method'] ?? 'email');
    $contact = sanitize_text_field($_POST['contact'] ?? '');

    if (empty($post_id)) wp_send_json_error(['message' => 'Conteúdo não identificado.']);
    if (!in_array($method, ['email', 'whatsapp'])) wp_send_json_error(['message' => 'Método inválido.']);

    if ($method === 'email') {
        $contact = sanitize_email($contact);
        if (!is_email($contact)) wp_send_json_error(['message' => 'Por favor, introduza um email válido.']);
    } else {
        $contact = preg_replace('/[^0-9+]/', '', $contact);
        if (strlen($contact) < 9) wp_send_json_error(['message' => 'Por favor, introduza um número de WhatsApp válido.']);
    }

    global $wpdb;
    $t = $wpdb->prefix . 'imz_presave_subscribers';

    // Verificar duplicado
    $exists = $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM $t WHERE post_id = %d AND contact = %s",
        $post_id, $contact
    ));
    if ($exists) wp_send_json_error(['message' => 'Já está inscrito para notificação deste lançamento.']);

    $ins = $wpdb->insert($t, [
        'post_id' => $post_id,
        'notify_method' => $method,
        'contact' => $contact,
        'subscribed_at' => current_time('mysql'),
    ]);

    if ($ins) {
        $music_title = get_the_title($post_id) ?: 'Novo lançamento';
        $msg = $method === 'email'
            ? 'Inscrito com sucesso! Receberá um email quando "' . esc_html($music_title) . '" for lançado.'
            : 'Inscrito com sucesso! Receberá uma mensagem no WhatsApp quando "' . esc_html($music_title) . '" for lançado.';
        wp_send_json_success(['message' => $msg]);
    } else {
        wp_send_json_error(['message' => 'Erro ao registar. Tente novamente.']);
    }
}

// =============================================================================
// ADMIN — PRE-SAVE MANAGER
// =============================================================================
add_action('admin_menu', 'imz_register_presave_menu');
function imz_register_presave_menu() {
    global $wpdb;
    $t = $wpdb->prefix . 'imz_presave_subscribers';
    $pending = 0;
    if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $t)) === $t)
        $pending = (int) $wpdb->get_var("SELECT COUNT(DISTINCT post_id) FROM $t WHERE notified = 0");
    $label = 'Pré-Lançamentos' . ($pending > 0 ? ' <span class="awaiting-mod">' . $pending . '</span>' : '');

    add_submenu_page(imz_admin_parent_slug(), 'Pré-Lançamentos', $label, 'manage_options', 'imz_presave_manager', 'imz_render_presave_manager_page');
}

function imz_render_presave_manager_page() {
    global $wpdb;
    $t = $wpdb->prefix . 'imz_presave_subscribers';

    // Ação: marcar como notificado e apagar dados
    if (isset($_GET['action'], $_GET['presave_post_id']) && check_admin_referer('imz_presave_action')) {
        $pid = absint($_GET['presave_post_id']);
        $action = sanitize_key($_GET['action']);
        if ($action === 'notified') {
            $wpdb->delete($t, ['post_id' => $pid]);
            echo '<div class="notice notice-success is-dismissible"><p>Todos os inscritos de "' . esc_html(get_the_title($pid)) . '" foram marcados como notificados e os dados foram apagados.</p></div>';
        }
    }

    // Agrupar por post_id
    $posts = $wpdb->get_results("SELECT post_id, COUNT(*) as total, SUM(notify_method = 'email') as total_email, SUM(notify_method = 'whatsapp') as total_whatsapp FROM $t WHERE notified = 0 GROUP BY post_id ORDER BY total DESC");

    ?>
    <div class="wrap">
        <h1>Pré-Lançamentos — Inscritos para Notificação</h1>
        <p class="description">Quando o conteúdo for lançado, exporte os contactos, notifique os inscritos e depois marque como notificado para apagar os dados.</p>

        <?php if (empty($posts)): ?>
            <div class="notice notice-info"><p>Nenhum pré-lançamento com inscritos pendentes.</p></div>
        <?php else: ?>
            <table class="wp-list-table widefat fixed striped" style="margin-top:16px;">
                <thead>
                    <tr>
                        <th>Conteúdo</th>
                        <th width="120">Data Lançamento</th>
                        <th width="80">Email</th>
                        <th width="80">WhatsApp</th>
                        <th width="80">Total</th>
                        <th width="200">Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($posts as $p):
                        $mt = get_the_title($p->post_id) ?: '#' . $p->post_id;
                        $rd = get_post_meta($p->post_id, '_imz_release_date', true);
                        $nonce = wp_create_nonce('imz_presave_action');
                        $detail_url = admin_url('edit.php?post_type=impulsionamento&page=imz_presave_manager&view=' . $p->post_id);
                    ?>
                    <tr>
                        <td><a href="<?php echo esc_url($detail_url); ?>" style="font-weight:600;"><?php echo esc_html($mt); ?></a></td>
                        <td><?php echo esc_html($rd ?: '—'); ?></td>
                        <td style="text-align:center;font-weight:600;"><?php echo $p->total_email; ?></td>
                        <td style="text-align:center;font-weight:600;"><?php echo $p->total_whatsapp; ?></td>
                        <td style="text-align:center;font-weight:700;font-size:16px;"><?php echo $p->total; ?></td>
                        <td>
                            <a href="<?php echo esc_url($detail_url); ?>" class="button button-small">Ver Inscritos</a>
                            <a href="<?php echo esc_url(add_query_arg(['page'=>'imz_presave_manager','action'=>'notified','presave_post_id'=>$p->post_id,'_wpnonce'=>$nonce], admin_url('edit.php?post_type=impulsionamento'))); ?>"
                               class="button button-small button-primary"
                               onclick="return confirm('Confirma que já notificou todos os inscritos? Os dados serão apagados.');">
                                ✓ Já Notifiquei
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>

        <?php
        // Vista de detalhe — lista de inscritos
        if (isset($_GET['view']) && $pid = absint($_GET['view'])):
            $subs = $wpdb->get_results($wpdb->prepare("SELECT * FROM $t WHERE post_id = %d AND notified = 0 ORDER BY subscribed_at DESC", $pid));
            $mt = get_the_title($pid) ?: '#' . $pid;
        ?>
        <div style="margin-top:30px;">
            <h2>Inscritos para "<?php echo esc_html($mt); ?>"</h2>

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-top:16px;">
                <!-- EMAILS -->
                <div class="postbox">
                    <div class="postbox-header"><h2 class="hndle">&#9993; Email (<?php echo count(array_filter($subs, function($s){return $s->notify_method==='email';})); ?>)</h2></div>
                    <div class="inside">
                        <?php
                        $emails = array_filter($subs, function($s){return $s->notify_method === 'email';});
                        if ($emails):
                            $email_list = implode(', ', array_map(function($s){return $s->contact;}, $emails));
                        ?>
                            <textarea class="large-text" rows="4" readonly onclick="this.select();"><?php echo esc_textarea($email_list); ?></textarea>
                            <p class="description">Copie e cole os emails para enviar a notificação.</p>
                            <table class="widefat striped" style="margin-top:10px;">
                                <?php foreach ($emails as $s): ?>
                                <tr><td><code><?php echo esc_html($s->contact); ?></code></td><td style="font-size:12px;color:#888;"><?php echo date_i18n('d/m/Y H:i', strtotime($s->subscribed_at)); ?></td></tr>
                                <?php endforeach; ?>
                            </table>
                        <?php else: ?>
                            <p style="color:#888;">Nenhum inscrito por email.</p>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- WHATSAPP -->
                <div class="postbox">
                    <div class="postbox-header"><h2 class="hndle">&#128242; WhatsApp (<?php echo count(array_filter($subs, function($s){return $s->notify_method==='whatsapp';})); ?>)</h2></div>
                    <div class="inside">
                        <?php
                        $phones = array_filter($subs, function($s){return $s->notify_method === 'whatsapp';});
                        if ($phones):
                            $phone_list = implode("\n", array_map(function($s){return $s->contact;}, $phones));
                        ?>
                            <textarea class="large-text" rows="4" readonly onclick="this.select();"><?php echo esc_textarea($phone_list); ?></textarea>
                            <p class="description">Copie os números para enviar via WhatsApp.</p>
                            <table class="widefat striped" style="margin-top:10px;">
                                <?php foreach ($phones as $s): ?>
                                <tr><td><code><?php echo esc_html($s->contact); ?></code></td><td style="font-size:12px;color:#888;"><?php echo date_i18n('d/m/Y H:i', strtotime($s->subscribed_at)); ?></td></tr>
                                <?php endforeach; ?>
                            </table>
                        <?php else: ?>
                            <p style="color:#888;">Nenhum inscrito por WhatsApp.</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
    <?php
}
