<?php

/**
 * 1 - CREATE CUSTOM POST TYPES
 */
require plugin_dir_path( __FILE__ ) . '1-post-types.php';

/**
 * 2 - CREATE DASHBOARD & MENUS
 */
require plugin_dir_path( __FILE__ ) . '2-dashboard-page.php';

/**
 * 3 - SSQ Media
 */
require plugin_dir_path( __FILE__ ) . '3-ssq-media.php';

/**
 * 5 - Shortcodes 
 */
require plugin_dir_path( __FILE__ ) . '5-shortcodes.php';

/**
 * 6 - Patterns 
 */
require plugin_dir_path( __FILE__ ) . '6-patterns.php';

/**
 * 	blocks v2 (php)
 */
require plugin_dir_path( __FILE__ ) . 'blocks-v2.php';

/**
 * Get authentication hash for API request
 * 
 * Returns either an empty string or a base64 encoded string 
 */
function scroll_sequence_get_api_auth_hash(){

    // use Freemius' PHP SDK and to get secret_key
    $site = freemius_scrollsequence()->get_site(); // when newly actiavted, this will return false, because the site is not registered yet
    if ( ! $site ) {
        $site_private_key = '';
        $fs_site_id = '';
        return '';
    } else {
        $site_private_key = $site->secret_key;
        $fs_site_id = $site->id;
    }

    // create the signature that verifies we own this license and install.
    $nonce =  gmdate('Y-m-d'); //"2025-04-25";
    $pk_hash = hash('sha512', $site_private_key . '|' . $nonce);
    $authentication_string = base64_encode($pk_hash . '|' . $nonce.'|'.$fs_site_id);    
    return $authentication_string;
}

/**
 *  3 - EDITOR - localize editor js with freemius data
 */
function scroll_sequence_localize_editor() {

    // This function is also called in 2-dashboard-page.php
    $data = array(
        'current_plan' => freemius_scrollsequence()->get_plan_name(), // careful: returns "PLAN_NAME" if not registered/tracking allowed, also returns "free" in trial
        'fs_auth_hash' => scroll_sequence_get_api_auth_hash(), // this is the hash used to authenticate the API request
        'scrollSequenceApiUrl' => SCROLLSEQUENCE_API_URL,
        
        'siteUrl' => esc_url( get_site_url() ),
        'pluginDir' => plugin_dir_url( __FILE__ ), // not sure where this is used, returns the v2/ folder url
        'wpApiSettings' => [
            'root' => esc_url_raw( rest_url() ),
            'nonce' => wp_create_nonce( 'wp_rest' ),
            //'versionString' => 'todo' // this property is present on the standard wpApiRoot, i guess I am going to need it at some point
        ], 
        'breakpoints' => get_option( 'scroll_sequence_breakpoints' ),
        'imageSizesWp' => scroll_sequence_get_image_sizes(),
        'trackingAllowed' => freemius_scrollsequence()->is_registered() && freemius_scrollsequence()->is_tracking_allowed() ? "1" : "0", // we need string "1" or "0" to convert to boolean in JS
        'adminUrl' => esc_url( get_admin_url() ), // for links to admin pages
        'isTrial' => freemius_scrollsequence()->is_trial() ? "1" : "0", // we need string "1" or "0" to convert to boolean in JS
    );
    wp_register_script( 'scroll-sequence-localized', '', [], SCROLLSEQUENCE_VERSION, true );
    wp_enqueue_script( 'scroll-sequence-localized' );
    wp_localize_script('scroll-sequence-localized', 'scroll_sequence_editor_data', $data);    
}
add_action( 'enqueue_block_editor_assets', 'scroll_sequence_localize_editor' );

/**
 * Get information about available image sizes
 * see: https://developer.wordpress.org/reference/functions/get_intermediate_image_sizes/
 */

function scroll_sequence_get_image_sizes( $size = '' ) {
	$wp_additional_image_sizes = wp_get_additional_image_sizes();

	$sizes = array();
	$get_intermediate_image_sizes = get_intermediate_image_sizes();

	// Create the full array with sizes and crop info
	foreach( $get_intermediate_image_sizes as $_size ) {
		if ( in_array( $_size, array( 'thumbnail', 'medium', 'large' ) ) ) {
			$sizes[ $_size ]['width'] = get_option( $_size . '_size_w' );
			$sizes[ $_size ]['height'] = get_option( $_size . '_size_h' );
			$sizes[ $_size ]['crop'] = (bool) get_option( $_size . '_crop' );
		} elseif ( isset( $wp_additional_image_sizes[ $_size ] ) ) {
			$sizes[ $_size ] = array( 
				'width' => $wp_additional_image_sizes[ $_size ]['width'],
				'height' => $wp_additional_image_sizes[ $_size ]['height'],
				'crop' =>  $wp_additional_image_sizes[ $_size ]['crop']
			);
		}
	}

	// Get only 1 size if found
	if ( $size ) {
		if( isset( $sizes[ $size ] ) ) {
			return $sizes[ $size ];
		} else {
			return false;
		}
	}
	return $sizes;
}







































/**
 * Register Attachments Custom Metadata
 * To store the scroll_sequence_flag metadata, you need to register it in WP
 * This ensures the metadata is saved and accessible.
 */
/*
function scroll_sequence_register_attachment_meta() {
    register_meta('post', 'scroll_sequence_flag', [
        'type'         => 'boolean',
        'description'  => 'Flag to indicate if the image is associated with Scrollsequence',
        'single'       => true,
        'show_in_rest' => true, // Make it accessible via the REST API
    ]);
}
add_action('init', 'scroll_sequence_register_attachment_meta');
*/
/**
 * Modify the REST API query for attachments
 * see: https://developer.wordpress.org/reference/hooks/rest_this-post_type_query/
 * Usage: (currently used only in TabPlay.tsx)
 *               const response = await apiFetch({
 *                   path: '/wp/v2/media?scroll_sequence_flag=true',
 *               });
 */
/*
function scroll_sequence_query_attachment_by_flag($args, $request) {
	if(isset($request["scroll_sequence_flag"]) ) {
		$args['meta_key'] = 'scroll_sequence_flag';
		$args['meta_value'] = true; //intval($request["scroll_sequence_flag"]);
	}		
	return $args;
}
add_filter('rest_attachment_query', 'scroll_sequence_query_attachment_by_flag', 10, 2);
*/


/**
 * Filter Media Library by Metadata
 * 
 * To hide or categorize images in the media library based on the scroll_sequence_flag, 
 * you can use the pre_get_posts hook in WordPress to modify the media query.
 * 
 * - Works only for the list view in media gallery, but not for the grid view 
 *  solution(?): https://wordpress.stackexchange.com/questions/271584/can-i-hide-the-attachments-from-media-which-i-uploaded-from-front-end
 * 
 * 
 */
// function scroll_sequence_filter_media_library($query) {
//     if (is_admin() && $query->is_main_query() && $query->get('post_type') === 'attachment') {
//         // Check if a specific filter is applied (e.g., show only unflagged images)
//         if (isset($_GET['scroll_sequence_filter']) && $_GET['scroll_sequence_filter'] === 'hide_flagged') {
//             $meta_query = $query->get('meta_query') ?: [];
//             $meta_query[] = [
//                 'key'     => 'scroll_sequence_flag',
//                 'value'   => true,
//                 'compare' => '!=', // Exclude flagged images
//             ];
//             $query->set('meta_query', $meta_query);
//         }
//     }
// }
// add_action('pre_get_posts', 'scroll_sequence_filter_media_library');



/**
 * 	blocks v1 (php)
 */
//require plugin_dir_path( __FILE__ ) . 'blocks-v1.php';




/**
 * Register breakpoints option
 */
/*
function scroll_sequence_register_breakpoints_option() {
    register_setting( 'general', 'scroll_sequence_breakpoints', [
        'type'              => 'array',
        'show_in_rest'      => [
            'schema' => [
                'type'  => 'array',
                'items' => [
                    'type'       => 'object',
                    'properties' => [
                        'width'   => [
                            'type' => 'integer',
                        ],
                        'name' => [
                            'type' => 'string',
                        ],
                        'slug' => [
                            'type' => 'string',
                        ],
                        'locked' => [
                            'type' => 'boolean',
                        ],                        
                    ],
                    'required' => [ 'width', 'name', 'slug' ],
                ],
            ],
        ],
        'sanitize_callback' => 'sanitize_text_field',
        'default'           => [ // This exist here and also in SettingsBreakpoints.js
            [
                'width'   => 360,
                'name' => 'Mobile',
                'slug' => 'mobile',
                'locked' => true
            ],
            [
                'width'   => 780,
                'name' => 'Tablet',
                'slug' => 'tablet',
                'locked' => true
            ],
        ],
    ] );
}
add_action( 'init', 'scroll_sequence_register_breakpoints_option' );
*/








  