<?php

namespace Saswp\Api\Vendor\VendorGroup;
use Saswp\Api;
use Saswp\DTOs\Response\Vendor\VendorGroup\PropertyPostDTO;
use Saswp\Settings;
use WP_REST_Request;
class VendorGroupWordpressSitemapDownloadApi
{
    private Api $api;
    private Settings $settings;
    private PropertyPostDTO $propertyPostDTO;
    private array $uploadDir;
    private string $dirSitemap = '/sitemap/';
    private $apiUrl = "/api/vendor/vendor_group/wordpress/:token/download";

    public function __construct(){
        $this->api = new Api();
        $this->settings = new Settings();
        $this->uploadDir = wp_upload_dir();
        wp_sas_sitemap_files_autoupdate_database_table_exists();

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

        $result = $this->api->getResult();
        $this->processResult($result);
        return $result;
    }

    private function processResult($result){
        if(count($result['data'] ?? [])){
            $this->removeCurrentFiles();
        }
        foreach($result['data'] ?? [] as $entity){
            
            if(isset($entity['filepath'])) {
                $file_url = $entity['filepath'];
                $file_name = basename($file_url);
                $dirPath = $this->retrieveUploadPath();
                $this->createDir($dirPath);
                $file_path = $dirPath . $file_name;
                
                $response = wp_remote_get($file_url);
                if (!is_wp_error($response) && $response['response']['code'] === 200) {
                    $write = file_put_contents($file_path, $response['body']);
                    if($write){
                        $this->insertWpSasSitemapFiles($this->dirSitemap.$file_name);
                    }
                }
            }
        }
    }

    private function createDir($dirPath = '/tmp'){
        if(!is_dir($dirPath)){
            mkdir($dirPath);
        }
        return $this;
    }

    private function insertWpSasSitemapFiles(string $path){
        global $wpdb;

        $table_name = $wpdb->prefix . 'sas_sitemap_files';
    
        $wpdb->insert(
            $table_name,
            array(
                'path' => $path
            )
        );
    }

    public function retrieveWpSasSitemapFiles():array{
        global $wpdb;

        $table_name = $wpdb->prefix . 'sas_sitemap_files';
    
        try{
            $results = $wpdb->get_results(
                "SELECT {$table_name}.*
                    FROM {$table_name} "
            );
        }catch (\Exception){

        }
        
        
        return $results ?? [];
    }

    private function retrieveUploadPath(){
        return $this->uploadDir['basedir'] . $this->dirSitemap;
    }

    private function removeCurrentFiles(){
        $_files = $this->retrieveWpSasSitemapFiles();
        foreach($_files as $file){
            $fileToRemove = $this->uploadDir['basedir'].$file->path;
            unlink($fileToRemove);
        }
        $this->truncateWpSasSitemapFiles();
    }
   
    private function truncateWpSasSitemapFiles():self{
        global $wpdb;

        $table_name = $wpdb->prefix . 'sas_sitemap_files';
    
        $wpdb->query( "TRUNCATE $table_name" );
        return $this;
    }
}
