<?php
/**
 * PNB CMS Theme functions and definitions.
 *
 * @package WordPress
 * @subpackage PNB_CMS_Theme
 */

add_theme_support('post-thumbnails', ['post']);


/**
 * Add Second Featured Image Meta Box
 */
add_action('add_meta_boxes', 'add_second_featured_image_box');

function add_second_featured_image_box() {
    add_meta_box(
        'second_featured_image',
        'Second Featured Image',
        'render_second_featured_image',
        'post',
        'side',
        'low'
    );
}
function render_second_featured_image($post) {

    wp_nonce_field('save_second_featured_image', 'second_featured_image_nonce');

    $image_id = get_post_meta($post->ID, '_second_featured_image_id', true);

    ?>
    <div>
        <img id="second-featured-preview"
             src="<?php echo $image_id ? wp_get_attachment_url($image_id) : ''; ?>"
             style="max-width:100%;<?php echo $image_id ? '' : 'display:none;'; ?>" />

        <input type="hidden"
               id="second_featured_image_id"
               name="second_featured_image_id"
               value="<?php echo esc_attr($image_id); ?>">

        <p>
            <button type="button" class="button" id="upload_second_featured_image">
                <?php echo $image_id ? 'Change Image' : 'Set Image'; ?>
            </button>
            <button type="button" class="button" id="remove_second_featured_image"
                style="<?php echo $image_id ? '' : 'display:none;'; ?>">
                Remove
            </button>
        </p>
    </div>

    <script>
        jQuery(document).ready(function ($) {
            let mediaUploader;

            $('#upload_second_featured_image').click(function (e) {
                e.preventDefault();

                if (mediaUploader) {
                    mediaUploader.open();
                    return;
                }

                mediaUploader = wp.media({
                    title: 'Select Image',
                    button: { text: 'Use this image' },
                    multiple: false
                });

                mediaUploader.on('select', function () {
                    const attachment = mediaUploader.state().get('selection').first().toJSON();
                    $('#second_featured_image_id').val(attachment.id);
                    $('#second-featured-preview').attr('src', attachment.url).show();
                    $('#remove_second_featured_image').show();
                });

                mediaUploader.open();
            });

            $('#remove_second_featured_image').click(function () {
                $('#second_featured_image_id').val('');
                $('#second-featured-preview').hide();
                $(this).hide();
            });
        });
    </script>
    <?php
}
add_action('save_post', 'save_second_featured_image');

function save_second_featured_image($post_id) {

    if (!isset($_POST['second_featured_image_nonce']) ||
        !wp_verify_nonce($_POST['second_featured_image_nonce'], 'save_second_featured_image')) {
        return;
    }

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }

    if (!current_user_can('edit_post', $post_id)) {
        return;
    }

    if (isset($_POST['second_featured_image_id'])) {
        update_post_meta(
            $post_id,
            '_second_featured_image_id',
            intval($_POST['second_featured_image_id'])
        );
    }
}



/* =========================================================
 * BUTTON FIELDS
 * ========================================================= */

add_action('add_meta_boxes', 'pnb_add_button_field_box');
function pnb_add_button_field_box() {
    add_meta_box(
        'custom_post_button_field',
        'Buttons',
        'pnb_render_button_field_box',
        'post',
        'normal',
        'default'
    );
}

function pnb_render_button_field_box($post) {
    wp_nonce_field('pnb_save_button_fields', 'pnb_button_fields_nonce');

    $button_label = get_post_meta($post->ID, '_button_label_field', true);
    $button_url   = get_post_meta($post->ID, '_button_url_field', true);
    $card_features_field   = get_post_meta($post->ID, '_card_features_field', true);
    $banner_label1_text_box   = get_post_meta($post->ID, '_banner_label1_text_box', true);
    $banner_label2_text_box   = get_post_meta($post->ID, '_banner_label2_text_box', true);
    ?>
    <p>
        <label for="card_features_field">Card Features (Add comma (,) seperated)</label><br>
        <input type="text" id="card_features_field" name="card_features_field"
               value="<?php echo esc_attr($card_features_field); ?>" style="width:100%;">
    </p>
    <p>
        <label for="card_features_field">Banner Label1 Text Box (Add comma (,) seperated)</label><br>
        <input type="text" id="banner_label1_text_box" name="banner_label1_text_box"
               value="<?php echo esc_attr($banner_label1_text_box); ?>" style="width:100%;">
    </p>
    <p>
        <label for="card_features_field">Banner Label2 Text Box (Add comma (,) seperated)</label><br>
        <input type="text" id="banner_label2_text_box" name="banner_label2_text_box"
               value="<?php echo esc_attr($banner_label2_text_box); ?>" style="width:100%;">
    </p>
    <p>
        <label for="button_label_field">Button Label</label><br>
        <input type="text" id="button_label_field" name="button_label_field"
               value="<?php echo esc_attr($button_label); ?>" style="width:100%;">
    </p>

    <p>
        <label for="button_url_field">Button URL</label><br>
        <input type="url" id="button_url_field" name="button_url_field"
               value="<?php echo esc_url($button_url); ?>" style="width:100%;">
    </p>
    <?php
}

add_action('save_post', 'pnb_save_button_fields');
function pnb_save_button_fields($post_id) {

    if (
        !isset($_POST['pnb_button_fields_nonce']) ||
        !wp_verify_nonce($_POST['pnb_button_fields_nonce'], 'pnb_save_button_fields')
    ) {
        return;
    }

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;

    if (isset($_POST['card_features_field'])) {
        update_post_meta(
            $post_id,
            '_card_features_field',
            sanitize_text_field($_POST['card_features_field'])
        );
    }
    if (isset($_POST['banner_label1_text_box'])) {
        update_post_meta(
            $post_id,
            '_banner_label1_text_box',
            sanitize_text_field($_POST['banner_label1_text_box'])
        );
    }
    if (isset($_POST['banner_label2_text_box'])) {
        update_post_meta(
            $post_id,
            '_banner_label2_text_box',
            sanitize_text_field($_POST['banner_label2_text_box'])
        );
    }
    
    
    if (isset($_POST['button_label_field'])) {
        update_post_meta(
            $post_id,
            '_button_label_field',
            sanitize_text_field($_POST['button_label_field'])
        );
    }

    if (isset($_POST['button_url_field'])) {
        update_post_meta(
            $post_id,
            '_button_url_field',
            esc_url_raw($_POST['button_url_field'])
        );
    }
}

/* =========================================================
 * CARD FIELDS
 * ========================================================= */

add_action('add_meta_boxes', 'pnb_add_cards_field_box');
function pnb_add_cards_field_box() {
    add_meta_box(
        'custom_post_cards_field',
        'Cards Data',
        'pnb_render_cards_field_box',
        'post',
        'normal',
        'default'
    );
}

function pnb_render_cards_field_box($post) {

    wp_nonce_field('pnb_save_cards_fields', 'pnb_cards_fields_nonce');

    $is_most_popular   = get_post_meta($post->ID, '_is_most_popular', true);
    $card_fee_label    = get_post_meta($post->ID, '_card_fee_label', true);
    $card_fee_amount   = get_post_meta($post->ID, '_card_fee_amount', true);
    $credit_limit_label= get_post_meta($post->ID, '_credit_limit_label', true);
    $limit_text        = get_post_meta($post->ID, '_limit_text', true);
    ?>
    <p>
        <label>
            <input type="checkbox" name="is_most_popular" value="1" <?php checked($is_most_popular, '1'); ?>>
            Most Popular
        </label>
    </p>

    <p>
        <label>Card Fee Label</label><br>
        <input type="text" name="card_fee_label" value="<?php echo esc_attr($card_fee_label); ?>" style="width:100%;">
    </p>

    <p>
        <label>Card Fee Amount</label><br>
        <input type="text" name="card_fee_amount" value="<?php echo esc_attr($card_fee_amount); ?>" style="width:100%;">
    </p>

    <p>
        <label>Credit Limit Label</label><br>
        <input type="text" name="credit_limit_label" value="<?php echo esc_attr($credit_limit_label); ?>" style="width:100%;">
    </p>

    <p>
        <label>Limit Text</label><br>
        <input type="text" name="limit_text" value="<?php echo esc_attr($limit_text); ?>" style="width:100%;">
    </p>
    <?php
}

add_action('save_post', 'pnb_save_cards_fields');
function pnb_save_cards_fields($post_id) {

    if (
        !isset($_POST['pnb_cards_fields_nonce']) ||
        !wp_verify_nonce($_POST['pnb_cards_fields_nonce'], 'pnb_save_cards_fields')
    ) {
        return;
    }

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;

    // Checkbox
    if (isset($_POST['is_most_popular'])) {
        update_post_meta($post_id, '_is_most_popular', '1');
    } else {
        delete_post_meta($post_id, '_is_most_popular');
    }

    update_post_meta($post_id, '_card_fee_label', sanitize_text_field($_POST['card_fee_label'] ?? ''));
    update_post_meta($post_id, '_card_fee_amount', sanitize_text_field($_POST['card_fee_amount'] ?? ''));
    update_post_meta($post_id, '_credit_limit_label', sanitize_text_field($_POST['credit_limit_label'] ?? ''));
    update_post_meta($post_id, '_limit_text', sanitize_text_field($_POST['limit_text'] ?? ''));
}



// API


add_action('rest_api_init', function () {
    register_rest_route('pnb-api/v1', '/cards', [
        'methods'  => 'POST',
        'callback' => 'pnb_api_get_cards',
        'permission_callback' => 'pnb_api_key_check', // custom API key check
    ]);
    register_rest_route('pnb-api/v1', '/slider', [
        'methods'  => 'POST',
        'callback' => 'pnb_api_get_slider',
        'permission_callback' => 'pnb_api_key_check', // custom API key check
    ]);
    register_rest_route('pnb-api/v1', '/offer-text', [
        'methods'  => 'POST',
        'callback' => 'pnb_api_get_offer_text',
        'permission_callback' => 'pnb_api_key_check', // custom API key check
    ]);
});
function pnb_api_key_check($request) {
    $api_key = $request->get_header('x-api-key'); // client must send this header
    if ($api_key && $api_key === PNB_API_KEY) {
        return true; // authorized
    }
    return new WP_Error('unauthorized', 'Invalid API key', ['status' => 401]);
}
function pnb_api_get_cards($request) {
    $categories = get_categories([
        'taxonomy'   => 'category',
        'include' => [3],
        'hide_empty' => true,
    ]);
    $response = [];
    foreach ($categories as $category) {
        // Get posts in this category
        $posts = get_posts([
            'post_type'      => 'post',
            'posts_per_page' => 100,
            'post_status'    => 'publish',
            'category'       => $category->term_id,
        ]);

        $posts_data = [];

        foreach ($posts as $post) {
            $tags = wp_get_post_tags($post->ID, ['fields' => 'names']);
            $categories_names = wp_get_post_categories($post->ID, ['fields' => 'names']);
            $featured_image = get_the_post_thumbnail_url($post->ID, 'full');
            $second_image_id = (int) get_post_meta($post->ID, '_second_featured_image_id', true);
            $featured_image2 = $second_image_id ? wp_get_attachment_url($second_image_id) : '';
            $expert = get_post_meta($post->ID, 'expert', true);
            $excerpt = !empty($post->post_excerpt) ? $post->post_excerpt : '';

            $posts_data[] = [
                'id'             => $post->ID,
                'title'          => get_the_title($post),
                'description'    => apply_filters('the_content', $post->post_content),
                'excerpt'        => $excerpt,
                'tags'           => $tags,
                'categories'     => $categories_names,
                'featured_image' => $featured_image,
                'featured_image2' => $featured_image2,
                'card_features' => get_post_meta($post->ID, '_card_features_field', true),
                'banner_label1_text_box' => get_post_meta($post->ID, '_banner_label1_text_box', true),
                'banner_label2_text_box' => get_post_meta($post->ID, '_banner_label2_text_box', true),
                'card_data'      => [
                    'button_label'       => get_post_meta($post->ID, '_button_label_field', true),
                    'button_url'         => get_post_meta($post->ID, '_button_url_field', true),
                    'is_most_popular'    => (bool) get_post_meta($post->ID, '_is_most_popular', true),
                    'card_fee_label'     => get_post_meta($post->ID, '_card_fee_label', true),
                    'card_fee_amount'    => get_post_meta($post->ID, '_card_fee_amount', true),
                    'credit_limit_label' => get_post_meta($post->ID, '_credit_limit_label', true),
                    'limit_text'         => get_post_meta($post->ID, '_limit_text', true),
                ],
            ];
        }

        // Only add category if it has posts
        if (!empty($posts_data)) {
            $response[] = [
                'category_id'   => $category->term_id,
                'category_name' => $category->name,
                'category_slug' => $category->slug,
                'posts'         => $posts_data,
            ];
        }
    }
    return rest_ensure_response($response);
}

function pnb_api_get_slider($request) {
    $categories = get_categories([
        'taxonomy'   => 'category',
        'include' => [1],
        'hide_empty' => true,
    ]);
    $response = [];
    foreach ($categories as $category) {
        // Get posts in this category
        $posts = get_posts([
            'post_type'      => 'post',
            'posts_per_page' => 100,
            'post_status'    => 'publish',
            'category'       => $category->term_id,
        ]);

        $posts_data = [];
        
        foreach ($posts as $post) {
            $tags = wp_get_post_tags($post->ID, ['fields' => 'names']);
            $categories_names = wp_get_post_categories($post->ID, ['fields' => 'names']);
            $featured_image = get_the_post_thumbnail_url($post->ID, 'full');
            
            $second_image_id = (int) get_post_meta($post->ID, '_second_featured_image_id', true);
            $featured_image2 = $second_image_id ? wp_get_attachment_url($second_image_id) : '';
            $expert = get_post_meta($post->ID, 'expert', true);
            $excerpt = !empty($post->post_excerpt) ? $post->post_excerpt : '';

            $posts_data[] = [
                'id'             => $post->ID,
                'title'          => get_the_title($post),
                'description'    => apply_filters('the_content', $post->post_content),
                'excerpt'        => $excerpt,
                'tags'           => $tags,
                'categories'     => $categories_names,
                'featured_image' => $featured_image,
                'featured_image2' => $featured_image2,
                'card_features' => get_post_meta($post->ID, '_card_features_field', true),
                'banner_label1_text_box' => get_post_meta($post->ID, '_banner_label1_text_box', true),
                'banner_label2_text_box' => get_post_meta($post->ID, '_banner_label2_text_box', true),
                'card_data'      => [
                    'button_label'       => get_post_meta($post->ID, '_button_label_field', true),
                    'button_url'         => get_post_meta($post->ID, '_button_url_field', true),
                    'is_most_popular'    => (bool) get_post_meta($post->ID, '_is_most_popular', true),
                    'card_fee_label'     => get_post_meta($post->ID, '_card_fee_label', true),
                    'card_fee_amount'    => get_post_meta($post->ID, '_card_fee_amount', true),
                    'credit_limit_label' => get_post_meta($post->ID, '_credit_limit_label', true),
                    'limit_text'         => get_post_meta($post->ID, '_limit_text', true),
                ],
            ];
        }

        // Only add category if it has posts
        if (!empty($posts_data)) {
            $response[] = [
                'category_id'   => $category->term_id,
                'category_name' => $category->name,
                'category_slug' => $category->slug,
                'posts'         => $posts_data,
            ];
        }
    }
    return rest_ensure_response($response);
}

function pnb_api_get_offer_text($request) {
    $categories = get_categories([
        'taxonomy'   => 'category',
        'include' => [2],
        'hide_empty' => true,
    ]);
    $response = [];
    foreach ($categories as $category) {
        // Get posts in this category
        $posts = get_posts([
            'post_type'      => 'post',
            'posts_per_page' => 100,
            'post_status'    => 'publish',
            'category'       => $category->term_id,
        ]);

        $posts_data = [];

        foreach ($posts as $post) {
            $tags = wp_get_post_tags($post->ID, ['fields' => 'names']);
            $categories_names = wp_get_post_categories($post->ID, ['fields' => 'names']);
            $featured_image = get_the_post_thumbnail_url($post->ID, 'full');
            $second_image_id = (int) get_post_meta($post->ID, '_second_featured_image_id', true);
            $featured_image2 = $second_image_id ? wp_get_attachment_url($second_image_id) : '';
            $expert = get_post_meta($post->ID, 'expert', true);
            $excerpt = !empty($post->post_excerpt) ? $post->post_excerpt : '';

            $posts_data[] = [
                'id'             => $post->ID,
                'title'          => get_the_title($post),
                'description'    => apply_filters('the_content', $post->post_content),
                'excerpt'        => $excerpt,
                'tags'           => $tags,
                'categories'     => $categories_names,
                'featured_image' => $featured_image,
                'featured_image2' => $featured_image2,
                'card_features' => get_post_meta($post->ID, '_card_features_field', true),
                'banner_label1_text_box' => get_post_meta($post->ID, '_banner_label1_text_box', true),
                'banner_label2_text_box' => get_post_meta($post->ID, '_banner_label2_text_box', true),
                'card_data'      => [
                    'button_label'       => get_post_meta($post->ID, '_button_label_field', true),
                    'button_url'         => get_post_meta($post->ID, '_button_url_field', true),
                    'is_most_popular'    => (bool) get_post_meta($post->ID, '_is_most_popular', true),
                    'card_fee_label'     => get_post_meta($post->ID, '_card_fee_label', true),
                    'card_fee_amount'    => get_post_meta($post->ID, '_card_fee_amount', true),
                    'credit_limit_label' => get_post_meta($post->ID, '_credit_limit_label', true),
                    'limit_text'         => get_post_meta($post->ID, '_limit_text', true),
                ],
            ];
        }

        // Only add category if it has posts
        if (!empty($posts_data)) {
            $response[] = [
                'category_id'   => $category->term_id,
                'category_name' => $category->name,
                'category_slug' => $category->slug,
                'posts'         => $posts_data,
            ];
        }
    }
    return rest_ensure_response($response);
}
// function pnb_api_get_cards($request) {
//     $categories = get_categories([
//         'taxonomy'   => 'category',
//         'hide_empty' => true,
//     ]);
//     $response = [];
//     foreach ($categories as $category) {
//         // Get posts in this category
//         $posts = get_posts([
//             'post_type'      => 'post',
//             'posts_per_page' => 100,
//             'post_status'    => 'publish',
//             'category'       => $category->term_id,
//         ]);

//         $posts_data = [];

//         foreach ($posts as $post) {
//             $tags = wp_get_post_tags($post->ID, ['fields' => 'names']);
//             $categories_names = wp_get_post_categories($post->ID, ['fields' => 'names']);
//             $featured_image = get_the_post_thumbnail_url($post->ID, 'full');
//             $expert = get_post_meta($post->ID, 'expert', true);
//             $excerpt = !empty($post->post_excerpt) ? $post->post_excerpt : wp_trim_words($post->post_content, 30);

//             $posts_data[] = [
//                 'id'             => $post->ID,
//                 'title'          => get_the_title($post),
//                 'description'    => apply_filters('the_content', $post->post_content),
//                 'excerpt'        => $excerpt,
//                 'expert'         => $expert,
//                 'tags'           => $tags,
//                 'categories'     => $categories_names,
//                 'featured_image' => $featured_image,
//                 'card_data'      => [
//                     'button_label'       => get_post_meta($post->ID, '_button_label_field', true),
//                     'button_url'         => get_post_meta($post->ID, '_button_url_field', true),
//                     'is_most_popular'    => (bool) get_post_meta($post->ID, '_is_most_popular', true),
//                     'card_fee_label'     => get_post_meta($post->ID, '_card_fee_label', true),
//                     'card_fee_amount'    => get_post_meta($post->ID, '_card_fee_amount', true),
//                     'credit_limit_label' => get_post_meta($post->ID, '_credit_limit_label', true),
//                     'limit_text'         => get_post_meta($post->ID, '_limit_text', true),
//                 ],
//             ];
//         }

//         // Only add category if it has posts
//         if (!empty($posts_data)) {
//             $response[] = [
//                 'category_id'   => $category->term_id,
//                 'category_name' => $category->name,
//                 'category_slug' => $category->slug,
//                 'posts'         => $posts_data,
//             ];
//         }
//     }
//     return rest_ensure_response($response);
// }

