<?php
namespace ONLINE_ADAv4;

use ONLINE_ADAv4\Helper;
use FoxORM\GibberishDetector\Gibberish;

add_action("wp_ajax_" . __NAMESPACE__ . "/save_changes", __NAMESPACE__ . "\\save_changes");
function save_changes(){
    Helper::verify_security($_POST);

    // Add capability check to ensure user has proper permissions
	if (!current_user_can('manage_options')) {
		wp_send_json_error('Unauthorized access', 403);
		wp_die();
	}
	
	// Add referrer check to ensure request comes from your admin pages
	$referer = wp_get_referer();
	if (!$referer || strpos($referer, admin_url()) !== 0) {
		wp_send_json_error('Invalid request origin', 403);
		wp_die();
	}
    
    foreach($_POST["modified"] AS $ID => $changes){

        foreach($changes AS $key => $value){
            $meta = false;
            switch ($key){
                case "decorative":
                    $meta = true;
                    
                    //If setting image to decorative
                    if($value == "true"){
                        $alt = get_post_meta($ID, "_wp_attachment_image_alt", true);
                        if($alt){
                            update_post_meta($ID, "_oadaas_original_alt", $alt);
                        }
                        
                        update_post_meta($ID, "_wp_attachment_image_alt", "*marked_decorative*");
                    }
                    //If unsetting decorative
                    if($value == "false"){
                        $alt = get_post_meta($ID, "_oadaas_original_alt", true);
                        
                        if($alt){
                            update_post_meta($ID, "_wp_attachment_image_alt", $alt);
                        }
                        if($alt == ""){
                            update_post_meta($ID, "_wp_attachment_image_alt", $alt);
                        }

                        delete_post_meta($ID, "_oadaas_original_alt");
                    }
                   
                    update_post_meta($ID, "_oadaas_decorative", $value);

                    break;
                case "alt":
                    $meta = true;
                    $decorative = get_post_meta($ID, "_oadaas_decorative", true );

                    //If updating the alt text but decorative is true
                    if($decorative == "true"){
                        update_post_meta($ID, "_oadaas_original_alt", $value);
                    }

                    if( empty($decorative) || $decorative == "false"){
                        update_post_meta($ID, "_wp_attachment_image_alt", $value);
                    }

                    break;
                case "title":
                    $key = "post_title";
                    break;
                case "description":
                    $key = "post_content";
                    break;
                case "caption":
                    $key = "post_excerpt";
                    break;
            }

            if(!$meta){
                $post_arr = [
                    "ID" => $ID,
                    $key => $value
                ];
                wp_update_post($post_arr);
            }
            
        }       
    }

    wp_send_json(["status" => "OK"]);
}

function process_alt_and_decorative($current_key){
    
    //Alt logic
    $decorative = filter_var(get_post_meta($ID, "_oadaas_decorative", true ), FILTER_VALIDATE_BOOLEAN);
    if($decorative){
        update_post_meta($ID, "_oadaas_original_alt", $value);
        update_post_meta($ID, "_wp_attachment_image_alt", "*marked_decorative*");
    }else{
        update_post_meta($ID, "_wp_attachment_image_alt", $value);
    }
}

add_action("wp_ajax_" . __NAMESPACE__ . "/get_list", __NAMESPACE__ . "\\get_list");

function get_list(){
    Helper::verify_security($_POST);

    // Add capability check to ensure user has proper permissions
	if (!current_user_can('manage_options')) {
		wp_send_json_error('Unauthorized access', 403);
		wp_die();
	}
	
	// Add referrer check to ensure request comes from your admin pages
	$referer = wp_get_referer();
	if (!$referer || strpos($referer, admin_url()) !== 0) {
		wp_send_json_error('Invalid request origin', 403);
		wp_die();
	}

    global $wpdb;
    $pageLength = $_POST["pageLength"];
    $current_page = $_POST["current_page"];
    $valid = $_POST["valid"];
    if(is_null($current_page)){ $current_page = 1; }
    $offset = $current_page === 1 ? 0 : ($current_page - 1) * $pageLength;

    $posts = $wpdb->get_results($wpdb->prepare(get_image_query($wpdb->prefix, $valid, true).' LIMIT %d, %d', [$offset, $pageLength])); // phpcs:ignore
    
    $data = [];
    foreach($posts AS $post){

        if(is_null($post->decorative) || $post->decorative == ""){ $post->decorative = false; }
        if(is_null($post->alt)){ $post->alt = ""; }

        $validation = [];
        
        $data[] = [
            "validation"    => get_validation($post->alt),
            "title"         => $post->title,
            "description"   => $post->description,
            "caption"       => $post->caption,
            "alt"           => $post->alt,
            "decorative"    => $post->decorative,
            "src"           => $post->src,
            "ID"            => $post->ID
        ];
        
    }
    
    wp_send_json(["status" => "OK", "data" => $data]);
}

function get_validation($str){
    //Test for: 
        //if this is gibberish
        //if this is less than 3 words
        //if this is just a sequence of numbers

    $validation = [];
    
    $too_few_words = str_word_count($str, 0, "&") < 3; //Warning
    $is_gibberish = Gibberish::test($str, Plugin::$instance->info["gibberish_matrix"], false); //Warning
    $is_numbers_only = ctype_digit($str); //Warning

    if($too_few_words){
        $validation["type"] = "warning";
        $validation["message"] = "Our validation algorithm has detected that this alt text may not be descriptive enough. Please verify and click confirm once you are sure it contains enough information";
        return $validation;
    }

    if($is_gibberish){
        $validation["type"] = "warning";
        $validation["message"] = "Our validation algorithm has detected that this alt text may not be human readable. Please verify and click confirm once you are sure it can be understood";
        return $validation;
    }

    if($is_numbers_only){
        $validation["type"] = "warning";
        $validation["message"] = "Our validation algorithm has detected that this alt text may not be descriptive enough. Please verify and click confirm once you are sure it contains enough information";
        return $validation;
    }

    $validation["type"] = "pass";
    $validation["message"] = "Valid alt text";
    return $validation;

}


add_action("wp_ajax_" . __NAMESPACE__ . "/get_image_count", __NAMESPACE__ . "\\get_image_count");

function get_image_count(){
    Helper::verify_security($_POST);

    // Add capability check to ensure user has proper permissions
	if (!current_user_can('manage_options')) {
		wp_send_json_error('Unauthorized access', 403);
		wp_die();
	}
	
	// Add referrer check to ensure request comes from your admin pages
	$referer = wp_get_referer();
	if (!$referer || strpos($referer, admin_url()) !== 0) {
		wp_send_json_error('Invalid request origin', 403);
		wp_die();
	}
    
    $valid = $_POST["valid"];
    global $wpdb;

    wp_send_json([
        "status"=> "OK", 
        "count" => $wpdb->get_results( get_image_query($wpdb->prefix, $valid))[0]->count  // phpcs:ignore
    ]);
}

function get_image_query($prefix, $valid, $full = false){
    
    $query = "SELECT COUNT(ID) as count FROM {$prefix}posts WHERE ID in ( SELECT p.ID";

    if($full){
        $query = "SELECT p.ID, p.post_title AS title, p.post_excerpt AS caption, p.post_content AS description,
        MAX(CASE WHEN {$prefix}postmeta.meta_key = '_oadaas_decorative' THEN {$prefix}postmeta.meta_value END) AS decorative,
        MAX(CASE WHEN {$prefix}postmeta.meta_key = '_wp_attachment_image_alt' THEN {$prefix}postmeta.meta_value END) AS 'alt', p.guid AS src";
    }
    if($valid == "invalid"){
        /*
        *   invalid = [ decorative not set - alt text not set ]
        *   invalid = [ decorative not set - alt text empty ]
        *   invalid = [ decorative false - alt text empty ]
        *   invalid = [ decorative false - alt text not set ]
        *
        */

        $query .= "
            FROM {$prefix}posts as p
            LEFT JOIN {$prefix}postmeta ON {$prefix}postmeta.post_id = p.ID
            WHERE post_type = 'attachment'
            AND post_mime_type != 'application/pdf'
            AND (
                (
                    NOT EXISTS (
                        SELECT * FROM {$prefix}postmeta
                        WHERE {$prefix}postmeta.meta_key = '_oadaas_decorative'
                        AND {$prefix}postmeta.post_id = p.ID
                    )
                    AND NOT EXISTS(
                        SELECT * FROM {$prefix}postmeta
                        WHERE {$prefix}postmeta.meta_key = '_wp_attachment_image_alt'
                        AND {$prefix}postmeta.post_id = p.ID
                    )
                )
                OR (
                    NOT EXISTS (
                        SELECT * FROM {$prefix}postmeta
                        WHERE {$prefix}postmeta.meta_key = '_oadaas_decorative'
                        AND {$prefix}postmeta.post_id = p.ID
                    )
                    AND EXISTS (
                        SELECT * FROM {$prefix}postmeta
                        WHERE {$prefix}postmeta.meta_key = '_wp_attachment_image_alt'
                        AND {$prefix}postmeta.meta_value = ''
                        AND {$prefix}postmeta.post_id = p.ID
                    )
                )
                OR (
                    EXISTS (
                        SELECT * FROM {$prefix}postmeta
                        WHERE {$prefix}postmeta.meta_key = '_oadaas_decorative'
                        AND {$prefix}postmeta.meta_value = 'false'
                        AND {$prefix}postmeta.post_id = p.ID
                    )
                    AND EXISTS (
                        SELECT * FROM {$prefix}postmeta
                        WHERE {$prefix}postmeta.meta_key = '_wp_attachment_image_alt'
                        AND {$prefix}postmeta.meta_value = ''
                        AND {$prefix}postmeta.post_id = p.ID
                    )
                )
                OR (
                    EXISTS (
                        SELECT * FROM {$prefix}postmeta
                        WHERE {$prefix}postmeta.meta_key = '_oadaas_decorative'
                        AND {$prefix}postmeta.meta_value = 'false'
                        AND {$prefix}postmeta.post_id = p.ID
                    )
                    AND NOT EXISTS (
                        SELECT * FROM {$prefix}postmeta
                        WHERE {$prefix}postmeta.meta_key = '_wp_attachment_image_alt'
                        AND {$prefix}postmeta.post_id = p.ID
                    )
                )
            )
            GROUP BY p.ID";
    }

    if($valid == "valid"){
        /*
        *   valid = [ decorative not set - alt text not empty ] 1
        *   valid = [ decorative false - alt text not empty ] 2
        *   valid = [ decorative true ] 3
        */

        $query .= "
            FROM {$prefix}posts as p
            LEFT JOIN {$prefix}postmeta ON {$prefix}postmeta.post_id = p.ID
            WHERE post_type = 'attachment'
            AND post_mime_type != 'application/pdf'

            AND ( 
                ({$prefix}postmeta.meta_key = '_oadaas_decorative' AND {$prefix}postmeta.meta_value = 'true')
                
                OR (                                                              
                    EXISTS (
                        SELECT * FROM {$prefix}postmeta
                        WHERE {$prefix}postmeta.meta_key = '_wp_attachment_image_alt'
                        AND {$prefix}postmeta.meta_value != ''
                        AND {$prefix}postmeta.post_id = p.ID
                    )
                )
            )
            GROUP BY p.ID";
    }

    if(!$full){ $query .= ")"; }
    
    return $query;
}