<?php
use Dompdf\Dompdf;
use Dompdf\Options;

// Force load DomPDF early
if (file_exists(__DIR__ . '/vendor/autoload.php')) {
    require_once __DIR__ . '/vendor/autoload.php';
}

/*
Plugin Name: Betting Personality Profiler Quiz
Plugin URI: https://gamblingsite.com
Description: An embeddable quiz plugin that helps users discover their betting personality and collects emails for deeper insights.
Version: 1.1
Author: GamblingSite.com
*/

function bppq_enqueue_assets() {
    wp_enqueue_style('bppq-style', plugin_dir_url(__FILE__) . 'css/bppq-style.css');
    wp_enqueue_script('bppq-script', plugin_dir_url(__FILE__) . 'js/bppq-script.js', array('jquery'), null, true);
    wp_localize_script('bppq-script', 'bppq_ajax_obj', array('ajax_url' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'bppq_enqueue_assets');

function bppq_quiz_shortcode() {
    ob_start();
    include plugin_dir_path(__FILE__) . 'partials/quiz-template.php';
    return ob_get_clean();
}
add_shortcode('betting_personality_quiz', 'bppq_quiz_shortcode');

function bppq_handle_quiz_submission() {
    header('Content-Type: application/json');

    $answers = isset($_POST['answers']) ? $_POST['answers'] : array();
    $email = sanitize_email($_POST['email']);

    if (empty($answers) || !is_array($answers)) {
        wp_send_json_error(array('message' => 'No answers received or format incorrect.'));
    }

    $score = array_count_values($answers);
    arsort($score);
    $top_type = array_key_first($score);

    $types = array(
        'A' => 'The Casual Bettor',
        'B' => 'The Analyst',
        'C' => 'The Risk-Taker',
        'D' => 'The Grinder',
        'E' => 'The Gut-Player'
    );

    $personality = isset($types[$top_type]) ? $types[$top_type] : 'Unknown';

    global $wpdb;
    $table = $wpdb->prefix . 'bppq_results';
    $wpdb->insert($table, array(
        'email' => $email,
        'answers' => maybe_serialize($answers),
        'personality' => $personality,
        'created_at' => current_time('mysql')
    ));

    if ($personality !== 'Unknown') {
        wp_send_json_success(array('personality' => $personality));
    } else {
        wp_send_json_error(array('message' => 'Could not determine personality.'));
    }
}
add_action('wp_ajax_bppq_submit_quiz', 'bppq_handle_quiz_submission');
add_action('wp_ajax_nopriv_bppq_submit_quiz', 'bppq_handle_quiz_submission');

add_action('wp_ajax_generate_pdf', 'bppq_generate_pdf');
add_action('wp_ajax_nopriv_generate_pdf', 'bppq_generate_pdf');
function bppq_generate_pdf() {
    if (!isset($_GET['personality'])) wp_die('No personality selected.');

    $personality = sanitize_text_field($_GET['personality']);

    $templates = array(
        'A' => 'the-casual-bettor-report-template-clean.html',
        'B' => 'the-analyst-report-template-clean.html',
        'C' => 'the-risk-taker-report-template-clean.html',
        'D' => 'the-grinder-report-template-clean.html',
        'E' => 'the-gut-player-report-template-clean.html'
    );

    $templateFile = __DIR__ . '/' . ($templates[$personality] ?? $templates['A']);
    if (!file_exists($templateFile)) wp_die("Template not found: $templateFile");

    $html = file_get_contents($templateFile);

    error_log("Loaded template path: $templateFile");
    error_log("HTML Preview: " . substr(strip_tags($html), 0, 100));

    $options = new Options();
    $options->set('isRemoteEnabled', true);
    $dompdf = new Dompdf($options);
    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();
    $dompdf->stream('betting-style-report.pdf', ["Attachment" => false]);
    exit;
}

function bppq_activate_plugin() {
    global $wpdb;
    $table = $wpdb->prefix . 'bppq_results';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        email varchar(255) DEFAULT '' NOT NULL,
        answers text NOT NULL,
        personality varchar(50) NOT NULL,
        created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id)
    ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}
register_activation_hook(__FILE__, 'bppq_activate_plugin');

function bppq_admin_menu() {
    add_menu_page('Quiz Results Export', 'Quiz Results', 'manage_options', 'bppq-results', 'bppq_render_results_page');
}
add_action('admin_menu', 'bppq_admin_menu');

function bppq_render_results_page() {
    if (isset($_POST['bppq_export'])) {
        global $wpdb;
        $table = $wpdb->prefix . 'bppq_results';
        $results = $wpdb->get_results("SELECT * FROM $table", ARRAY_A);

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="quiz_results.csv"');
        $output = fopen('php://output', 'w');
        fputcsv($output, array('ID', 'Email', 'Personality', 'Answers', 'Date'));

        foreach ($results as $row) {
            fputcsv($output, array($row['id'], $row['email'], $row['personality'], maybe_unserialize($row['answers']), $row['created_at']));
        }

        fclose($output);
        exit;
    }
    echo '<div class="wrap"><h1>Quiz Results Export</h1><form method="post"><input type="submit" name="bppq_export" class="button button-primary" value="Export CSV"></form></div>';
}
