<?php

namespace Saswp\Api\Vendor\VendorGroup;
use Saswp\Api;
use Saswp\DTOs\Response\Vendor\VendorGroup\PropertyPostDTO;
use Saswp\Settings;
use WP_REST_Request;
require_once ('wp-admin/includes/admin.php');
require_once ('wp-includes/post.php');
class VendorGroupWordpressPropertyPostApi
{
    private Api $api;
    private Settings $settings;
    private PropertyPostDTO $propertyPostDTO;
    private $apiUrl = "/api/vendor/vendor_group/wordpress_property/property/posts";

    public function __construct(){
        $this->api = new Api();
        $this->settings = new Settings();
    }
    public function __invoke(WP_REST_Request $wpRestRequest):array
    {
        $this->api
            ->setApiUrl($this->settings->getFullUrl())
            ->setApiUrlPath($this->apiUrl)
            ->setApiToken($this->settings->get("sas_api_token", ''))
            ->doRequest();

        $result = $this->api->getResult();
        if($this->settings->getSasPostUpdateFlag()){
            $this->processResult($result);
        }
        return $result;
    }

    private function processResult($result){
        foreach($result['data']['entities'] ?? [] as $entity){

            if(!isset($entity['id'])) { continue; }

            $ID = $this->retrieveWpPostByPostId($entity['id']);
            $_post = [
                'ID' => $ID,
                'post_title' => $entity['title'],
                'post_content' => $entity['description'],
                'post_status' => 'publish'
            ];
            $wpError = false;
            $wpPostId = wp_insert_post( $_post, $wpError );

            if($ID === 0){
                $this->insertWpSasPropertyPosts($entity['id'], $wpPostId);
                $this->insertThumbImage($wpPostId, $entity);
                $this->insertLocationMetadata($wpPostId, $entity);
            }
            $this->updateYoastMetadata($wpPostId, $entity);
        }
    }

    private function insertWpSasPropertyPosts(int $postId = 0, int $wpPostId=0){
        global $wpdb;

        $table_name = $wpdb->prefix . 'sas_property_posts';
    
        $wpdb->insert(
            $table_name,
            array(
                'post_id' => $postId,
                'wp_post_id' => $wpPostId
            )
        );
    }

    private function retrieveWpPostByPostId(int $postId = 0):int{
        global $wpdb;

        $table_name = $wpdb->prefix . 'sas_property_posts';
        $wp_table_name = $wpdb->prefix . 'posts';
    
        $results = $wpdb->get_results(
            "SELECT {$table_name}.*, {$wp_table_name}.ID as site_wp_post_id 
                FROM {$table_name} 
                LEFT JOIN {$wp_table_name} ON {$wp_table_name}.ID = {$table_name}.wp_post_id
                WHERE post_id = '{$postId}'"
        );
        if(isset($results[0]) && $results[0]->site_wp_post_id === null){
            $wpdb->delete(
                $table_name,
                array(
                    'post_id' => $postId
                )
            );
            $results[0]->wp_post_id = null;
        }
        return $results[0]->wp_post_id ?? 0;
    }

    private function insertThumbImage(int $wpPostId=0, array $entity=[]){
        $this->generateFeaturedImage($entity['image'] ?? '', $wpPostId);
    }

    private function insertLocationMetadata(int $wpPostId=0, array $entity=[]){
        add_post_meta( $wpPostId, "ne_lat", $entity['ne_lat'] ?? 0);
        add_post_meta( $wpPostId, "ne_lng", $entity['ne_lng'] ?? 0);
        add_post_meta( $wpPostId, "sw_lat", $entity['sw_lat'] ?? 0);
        add_post_meta( $wpPostId, "sw_lng", $entity['sw_lng'] ?? 0);
        add_post_meta( $wpPostId, "is_sas", 1);
    }

    private function updateYoastMetadata(int $wpPostId = 0, array $entity=[]){
        if(isset($entity["meta_description"]) && $entity["meta_description"] != ""){
            update_post_meta( $wpPostId, "_yoast_wpseo_metadesc", $entity['meta_description']);
        }
        if(isset($entity["meta_title"]) && $entity["meta_title"] != ""){
            update_post_meta( $wpPostId, "_yoast_wpseo_title", $entity['meta_title']);
        }
    }

    /**
    * Downloads an image from the specified URL and attaches it to a post as a post thumbnail.
    *
    * @param string $file    The URL of the image to download.
    * @param int    $post_id The post ID the post thumbnail is to be associated with.
    * @param string $desc    Optional. Description of the image.
    * @return string|WP_Error Attachment ID, WP_Error object otherwise.
    * Ref: https://wordpress.stackexchange.com/questions/40301/how-do-i-set-a-featured-image-thumbnail-by-image-url-when-using-wp-insert-post
    */
    function generateFeaturedImage( $file, $post_id, string $desc='' ){
        $file_array = array();
        // Set variables for storage, fix file filename for query strings.
        preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $file, $matches );
        if ( ! $matches ) {
             preg_match( '/^https:\/\/images\./i', $file, $matches );
             if ( ! $matches ) {
                return new \WP_Error( 'image_sideload_failed', __( 'Invalid image URL', 'searchandstay' ) );
             }
             $file_array['name'] = substr(md5(date("ymdhis").rand(0,100)), 0, 15).".jpg";
        }else{
            $file_array['name'] = basename( $matches[0] );
        }
    
        // Download file to temp location.
        $file_array['tmp_name'] = download_url( $file );
    
        // If error storing temporarily, return the error.
        if ( is_wp_error( $file_array['tmp_name'] ) ) {
            return $file_array['tmp_name'];
        }
    
        // Do the validation and storage stuff.
        $id = media_handle_sideload( $file_array, $post_id, $desc );
    
        // If error storing permanently, unlink.
        if ( is_wp_error( $id ) ) {
            @unlink( $file_array['tmp_name'] );
            return $id;
        }
        return set_post_thumbnail( $post_id, $id );
    
    }
}
