<?php 

if ( function_exists( 'add_theme_support' ) ) {
    add_theme_support( 'post-thumbnails' );
  
    function create_thumb() {
        add_image_size( 'thumbnail', 150, 150, true );
        add_image_size( 'medium', 400, 220, true );
        add_image_size( 'large', 768, 768 );
    }

    create_thumb();
}

// Create Custom Post Type (Admin Storage)

function register_contact_messages_cpt() {
    register_post_type('contact_message', [
        'labels' => [
            'name' => 'Contact Messages',
            'singular_name' => 'Contact Message'
        ],
        'public' => false,
        'show_ui' => true,
        'menu_icon' => 'dashicons-email',
        'supports' => ['title']
    ]);
}
// Handle Form Submission (Save Data)
add_action('init', 'register_contact_messages_cpt');
add_action('admin_post_submit_contact_form', 'handle_contact_form');
add_action('admin_post_nopriv_submit_contact_form', 'handle_contact_form');

function handle_contact_form() {

    if (!isset($_POST['contact_nonce']) || 
        !wp_verify_nonce($_POST['contact_nonce'], 'contact_form_nonce')) {
        wp_die('Security check failed');
    }

    $post_id = wp_insert_post([
        'post_type'   => 'contact_message',
        'post_title'  => sanitize_text_field($_POST['subject']),
        'post_status' => 'publish'
    ]);

    if ($post_id) {
        update_post_meta($post_id, 'name', sanitize_text_field($_POST['name']));
        update_post_meta($post_id, 'email', sanitize_email($_POST['email']));
        update_post_meta($post_id, 'contact_number', sanitize_text_field($_POST['contact_number']));
        update_post_meta($post_id, 'message', sanitize_textarea_field($_POST['message']));
    }

    wp_redirect(home_url());
    exit;
}
// Add Custom Columns
add_filter('manage_contact_message_posts_columns', function ($columns) {

    $new_columns = [];
    $new_columns['cb'] = $columns['cb']; // checkbox
    $new_columns['title'] = 'Subject';
    $new_columns['name'] = 'Name';
    $new_columns['email'] = 'Email';
    $new_columns['contact_number'] = 'Contact Number';
    $new_columns['message'] = 'Message';
    $new_columns['date'] = $columns['date'];

    return $new_columns;
});



// Fill Column Data
add_action('manage_contact_message_posts_custom_column', function ($column, $post_id) {

    switch ($column) {

        case 'name':
            echo esc_html(get_post_meta($post_id, 'name', true));
            break;

        case 'email':
            echo esc_html(get_post_meta($post_id, 'email', true));
            break;

        case 'contact_number':
            echo esc_html(get_post_meta($post_id, 'contact_number', true));
            break;

        case 'message':
            echo esc_html(wp_trim_words(
                get_post_meta($post_id, 'message', true),
                7,
                '…'
            ));
            break;
    }

}, 10, 2);

// Contact form FULL MESSAGE VIEW (ON CLICK)
add_action('add_meta_boxes', function () {
    add_meta_box(
        'contact_message_details',
        'Message Details',
        function ($post) {
            ?>
            <p><strong>Name:</strong> <?php echo esc_html(get_post_meta($post->ID, 'name', true)); ?></p>
            <p><strong>Email:</strong> <?php echo esc_html(get_post_meta($post->ID, 'email', true)); ?></p>
            <p><strong>Contact:</strong> <?php echo esc_html(get_post_meta($post->ID, 'contact_number', true)); ?></p>
            <p><strong>Message:</strong><br>
                <?php echo nl2br(esc_html(get_post_meta($post->ID, 'message', true))); ?>
            </p>
            <?php
        },
        'contact_message',
        'normal',
        'high'
    );
});


// Export Contact Messages as CSV 
// Add submenu page
add_action('admin_menu', function () {
    add_submenu_page(
        'edit.php?post_type=contact_message',
        'Export CSV',
        'Export CSV',
        'manage_options',
        'export-contact-csv',
        '__return_null' // temporary, we won't run export here
    );
});

// Hook CSV export to admin_init
add_action('admin_init', function () {
    if (isset($_GET['page']) && $_GET['page'] === 'export-contact-csv') {

        // Start output buffering to prevent any prior output breaking headers
        ob_start();

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename=contact-messages.csv');

        $output = fopen('php://output', 'w');

        fputcsv($output, ['Name', 'Email', 'Contact Number', 'Subject', 'Message']);

        $query = new WP_Query([
            'post_type' => 'contact_message',
            'posts_per_page' => -1
        ]);

        while ($query->have_posts()) {
            $query->the_post();

            fputcsv($output, [
                get_post_meta(get_the_ID(), 'name', true),
                get_post_meta(get_the_ID(), 'email', true),
                get_post_meta(get_the_ID(), 'contact_number', true),
                get_the_title(),
                get_post_meta(get_the_ID(), 'message', true),
            ]);
        }

        fclose($output);
        exit; // important: stop WordPress from outputting anything else
    }
});


// Create a Custom Post Type for Pre-Registration

// Register Pre-Registration CPT
add_action('init', function() {
    $labels = [
        'name' => 'Pre-Registrations',
        'singular_name' => 'Pre-Registration',
        'menu_name' => 'Pre-Registrations',
        'all_items' => 'All Pre-Registrations',
        'add_new_item' => 'Add New Pre-Registration',
    ];

    $args = [
        'labels' => $labels,
        'public' => false,
        'show_ui' => true,
        'show_in_menu' => true,
        'supports' => ['title'], // title can be student's name
    ];

    register_post_type('pre_registration', $args);
});



// Handle Pre-Registration Form Submission
add_action('wp_ajax_nopriv_submit_preregistration', 'handle_preregistration_form');
add_action('wp_ajax_submit_preregistration', 'handle_preregistration_form');

function handle_preregistration_form() {
    // Sanitize input
    $guardian_name = sanitize_text_field($_POST['guardian_name'] ?? '');
    $student_name = sanitize_text_field($_POST['student_name'] ?? '');
    $email = sanitize_email($_POST['email'] ?? '');
    $contact = sanitize_text_field($_POST['contact'] ?? '');
    $course = sanitize_text_field($_POST['course'] ?? '');

    // Create a new post
    $post_id = wp_insert_post([
        'post_type' => 'pre_registration',
        'post_title' => $student_name,
        'post_status' => 'publish',
    ]);

    if($post_id) {
        // Save custom fields
        update_post_meta($post_id, 'guardian_name', $guardian_name);
        update_post_meta($post_id, 'student_name', $student_name);
        update_post_meta($post_id, 'email', $email);
        update_post_meta($post_id, 'contact', $contact);
        update_post_meta($post_id, 'course', $course);

            // Send email to submitted email address
        $subject = "Pre-Registration Confirmation";
        $message = "Hello $guardian_name,\n\n";
        $message .= "Thank you for pre-registering your student, $student_name, for the $course course.\n";
        $message .= "We will contact you shortly.\n\n";
        $message .= "Best regards,\nYour School/Institute Name";

        $headers = ['Content-Type: text/plain; charset=UTF-8'];

        wp_mail($email, $subject, $message, $headers);

        wp_send_json_success('Form submitted successfully!');
    }

    wp_send_json_error('Failed to submit form.');
}


// Show Data of preresigtraion in Admin Panel (Columns)
// Add columns
add_filter('manage_pre_registration_posts_columns', function($columns){
    $columns['guardian_name'] = 'Guardian';
    $columns['email'] = 'Email';
    $columns['contact'] = 'Contact';
    $columns['course'] = 'Course';
    return $columns;
});

// Populate columns
add_action('manage_pre_registration_posts_custom_column', function($column, $post_id){
    switch($column){
        case 'guardian_name':
            echo esc_html(get_post_meta($post_id, 'guardian_name', true));
            break;
        case 'email':
            echo esc_html(get_post_meta($post_id, 'email', true));
            break;
        case 'contact':
            echo esc_html(get_post_meta($post_id, 'contact', true));
            break;
        case 'course':
            echo esc_html(get_post_meta($post_id, 'course', true));
            break;
    }
}, 10, 2);


// Export CSV for Pre-Registrations
// Add submenu page
add_action('admin_menu', function () {
    add_submenu_page(
        'edit.php?post_type=pre_registration',
        'Export CSV',
        'Export CSV',
        'manage_options',
        'export-pre-registration-csv',
        '__return_null'
    );
});

// CSV export
add_action('admin_init', function () {
    if (isset($_GET['page']) && $_GET['page'] === 'export-pre-registration-csv') {
        ob_start();
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename=pre-registrations.csv');

        $output = fopen('php://output', 'w');
        fputcsv($output, ['Guardian Name','Student Name','Email','Contact','Course']);

        $query = new WP_Query(['post_type'=>'pre_registration','posts_per_page'=>-1]);

        while($query->have_posts()){
            $query->the_post();
            fputcsv($output, [
                get_post_meta(get_the_ID(), 'guardian_name', true),
                get_post_meta(get_the_ID(), 'student_name', true),
                get_post_meta(get_the_ID(), 'email', true),
                get_post_meta(get_the_ID(), 'contact', true),
                get_post_meta(get_the_ID(), 'course', true),
            ]);
        }
        fclose($output);
        exit;
    }
});
