<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('memory_limit', '2048M');

include_once '../config.php';
//include_once "../config_profit_percentage.php";
include_once "../database1.php";

use Meilisearch\Client;


class Index extends database
{
    

    public function getProductsFromSubcategory()
    {
      
      $sql = 'SELECT t.* FROM (SELECT p1.cl_id AS id, p1.cl_name AS name, p1.cl_type AS type,  p1.cl_created_at AS created_at, p1.cl_manufacturer AS manufacturer,  p1.cl_supplier_price AS supplier_price, p1.cl_slug AS slug,p1.cl_image AS image,p1.cl_image_location AS image_location,p1.cl_cat_id AS category,p1.cl_sub_cat_id AS subcategory,p1.cl_brand_id AS brand, p1.cl_stock AS stock, p1.cl_small_specification AS small_specification FROM tb_product p1 '
              . ' INNER JOIN (SELECT cl_ean, MIN(cl_supplier_price) AS price FROM tb_product WHERE cl_deleted_at IS NULL GROUP BY cl_ean) AS p2 ON p1.cl_ean = p2.cl_ean AND p1.cl_supplier_price = p2.price   WHERE p1.cl_deleted_at IS NULL AND p1.cl_active=1 AND p1.cl_stock=1 AND p1.cl_supplier_price!=0  AND p1.cl_ean IS NOT NULL AND p1.cl_type="General" GROUP BY p1.cl_ean'
              //. ' UNION ALL '
              //. ' SELECT p.cl_id AS id,p.cl_name AS name, p.cl_type AS type, p.cl_created_at AS created_at, p.cl_manufacturer AS manufacturer, p.cl_supplier_price AS supplier_price, p.cl_slug AS slug, p.cl_image AS image, p.cl_image_location AS image_location,p.cl_cat_id AS category,p.cl_sub_cat_id AS subcategory,p.cl_brand_id AS brand, p.cl_stock AS stock FROM tb_product p WHERE p.cl_type="Variable" AND p.cl_active=1 GROUP BY p.cl_id '
              . ') AS t ORDER BY t.created_at DESC ';
      
        $response['data'] = $this->callQuery($sql);
        
        
        return $response;
    }
    
    public function getProductsFromSubcategoryVariables()
    {
        $sql = 'SELECT t.* FROM ('
              . ' SELECT p.cl_id AS id,p.cl_name AS name, p.cl_type AS type, p.cl_created_at AS created_at, p.cl_manufacturer AS manufacturer, p.cl_supplier_price AS supplier_price, p.cl_slug AS slug, p.cl_image AS image, p.cl_image_location AS image_location,p.cl_cat_id AS category,p.cl_sub_cat_id AS subcategory,p.cl_brand_id AS brand, 0 AS stock, p.cl_small_specification AS small_specification FROM tb_product p WHERE p.cl_type="Variable" AND p.cl_active=1 GROUP BY p.cl_id '
              . ') AS t ORDER BY t.created_at DESC ';
      
        $response['data'] = $this->callQuery($sql);
        
        
        return $response;
    }
    
    
    public function getOutOfStockProducts()
    {
        $sql = 'SELECT p1.cl_id AS id, p1.cl_name AS name, p1.cl_type AS type,  p1.cl_created_at AS created_at, p1.cl_manufacturer AS manufacturer,  p1.cl_supplier_price AS supplier_price, p1.cl_slug AS slug,p1.cl_image AS image,p1.cl_image_location AS image_location,p1.cl_cat_id AS category,p1.cl_sub_cat_id AS subcategory,p1.cl_brand_id AS brand, p1.cl_stock AS stock, p1.cl_small_specification AS small_specification FROM tb_product p1 '
              . ' INNER JOIN (SELECT cl_ean, MIN(cl_supplier_price) AS price FROM tb_product WHERE cl_deleted_at IS NULL GROUP BY cl_ean) AS p2 ON p1.cl_ean = p2.cl_ean AND p1.cl_supplier_price = p2.price   WHERE p1.cl_deleted_at IS NULL AND p1.cl_active=1 AND p1.cl_stock=0 AND p1.cl_supplier_price!=0  AND p1.cl_ean IS NOT NULL AND p1.cl_type="General" GROUP BY p1.cl_ean ORDER BY p1.cl_created_at DESC LIMIT 0,50000';
      
        $response['data'] = $this->callQuery($sql);
        return $response;
    }
    
    
    


   
}


function formatSmallSpecification(?string $html): string
{
    if (empty($html)) {
        return '';
    }

    $html = str_replace(["\r", "\n", "\t"], '', $html);

    // Remove table tags
    $html = preg_replace('/<table[^>]*>/', '', $html);
    $html = str_replace('</table>', '', $html);

    // Convert table structure to UL/LI
    $html = str_replace('<tbody>', '<ul class="product_list_small_specification">', $html);
    $html = str_replace('</tbody>', '</ul>', $html);

    $html = str_replace('<tr><td>', '<li>', $html);
    $html = str_replace('</td></tr>', '</li>', $html);

    $html = str_replace('<tr><th>', '<li>', $html);
    $html = str_replace('</th><td>', ': ', $html);

    return trim($html);
}

if(isset($_POST['page']) && is_numeric($_POST['page']))
{
  $page = $_POST['page'];
}

    $obj = new Index();

    $products = $obj->getProductsFromSubcategory();
    $productArray = $products['data'];
    foreach ($productArray as &$item) {
        $item['small_specification_formatted'] =
            formatSmallSpecification($item['small_specification'] ?? '');
    }
    unset($item);
    
    $client = new Client('http://51.178.41.179:7700', '6EVf0cuV7uE-PQiSyAmj2YanqeTiYFLqoWRYFr1l8PM');
    
    $client->deleteIndex('products1');
    

    $index = $client->index('products1');
    $index->addDocuments($productArray);
    $index->updateSortableAttributes([
        'created_at',
        'supplier_price'
        
      ]);
    
    $index->updateFilterableAttributes([
        'subcategory',
        'category',
        'brand',
        'name',
        'supplier_price'
        ]);
    
    
    
    
    /* variable */
    $variableProducts = $obj->getProductsFromSubcategoryVariables();
    $variableProductArray = $variableProducts['data'];
    foreach ($variableProductArray as &$item) {
        $item['small_specification_formatted'] =
            formatSmallSpecification($item['small_specification'] ?? '');
    }
    unset($item);
    $client = new Client('http://51.178.41.179:7700', '6EVf0cuV7uE-PQiSyAmj2YanqeTiYFLqoWRYFr1l8PM');
    
    $client->deleteIndex('variable');
    

    $variableIndex = $client->index('variable');
    $variableIndex->addDocuments($variableProductArray);
    $variableIndex->updateSortableAttributes([
        'created_at',
        'supplier_price'
        
      ]);
    
    $variableIndex->updateFilterableAttributes([
        'subcategory',
        'category',
        'brand',
        'name',
        'supplier_price'
        ]);
   
    
    /* Inactive */ 
    
    $products = $obj->getOutOfStockProducts();
    $productArray = $products['data'];
    
    foreach ($productArray as &$item) {
        $item['small_specification_formatted'] =
            formatSmallSpecification($item['small_specification'] ?? '');
    }
    unset($item);
    $client = new Client('http://51.178.41.179:7700', '6EVf0cuV7uE-PQiSyAmj2YanqeTiYFLqoWRYFr1l8PM');
    
    $client->deleteIndex('inactive_products');

    $indexInactive = $client->index('inactive_products');
    $indexInactive->addDocuments($productArray);
    $indexInactive->updateSortableAttributes([
        'created_at',
        'supplier_price'
        
      ]);
    
    $indexInactive->updateFilterableAttributes([
        'subcategory',
        'category',
        'brand',
        'name',
        'supplier_price'
        ]);