<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/aipma2025/include/config.php");
require_once(INCLUDE_PATH . "startup.php");
$alltables = new AllTables();

define('MAX_STRING', 8);
define('FIX_COUNTRY', true);                 

$hsnLabels = [];
$worldData = [];
$indiaData = [];



if (isset($_REQUEST['hsn_code']) || isset($_REQUEST['chapeter_code'])) 
{
    $to_country          = sanitize($_REQUEST['to_country'], SQL + HTML);
    $chaptercode          = intval($_REQUEST['chapeter_code']);
    
    $where = [];
    empty($to_country)          ? null : $where['import_to_country'] = $to_country;
    empty($chaptercode)         ? null : $where['Chapter'] = $chaptercode;


    $i = 0;
    $wherecondition = '';
    $newwherecondition = '';
    $imagearray = array();

    foreach ($where as $key => $value) 
    {
        if ($i == 0) 
        {
            $i++;        
            $wherecondition .= " WHERE $key = '$value' ";
        } 
        else 
        {
            $wherecondition .= " AND $key = '$value' ";
        }
    }



    if ($to_country) {
        $searchText = " Import in $to_country,";
    }

    if ($chaptercode) {
        $searchText .= " Chapter :  $chaptercode,";
    }

   
    $searchText = rtrim($searchText, ', ');


    if ($wherecondition)                                                                           
    {
        $searchsql = "SELECT * FROM " . TOP_25_WORLD_INDIA_EXPORTS_VIEW . " $wherecondition ORDER BY hsn_rank ASC";
    }

    $searchdata = $alltables->getInfo("", $searchsql);
    $searchdatacount = count($searchdata);


if ($searchdatacount)       
{
    
    // $displayCountryName = ucfirst(strtolower($to_country));
            $displayCountryName = strtoupper($to_country);        // Table header

    // Table header
    $rowheader .= "
    <tr>
        <th class='align-middle'>Sr. No.</th>
        <th class='align-middle'>HSN Product Code</th>
        <th class='align-middle'>Product Label</th>
        <th class='align-middle'>Country</th>
        <th class='hsn-header-blue'>Import from World to ".$displayCountryName."</th>
    
        <th class='hsn-header-yellow'>Import from India to ". $displayCountryName."</th>
        <th class='hsn-header-yellow'>India's Share % in 2023 in ".$displayCountryName."</th>
    </tr>";

    // Arrays for Chart.js
    $hsnLabels = [];
    $worldData = [];
    $indiaData = [];
    
    
    $imagearray = getHsnCodeImage($chaptercode, $hsn_imagecode);


    for ($i = 0; $i < $searchdatacount; $i++) 
    {
        $hsncode = $searchdata[$i]["HSNcode"];
        $hsncode_name = $searchdata[$i]["name"];
        $import_to_country = $searchdata[$i]["import_to_country"];
        $import_from_world = $searchdata[$i]["import_from_world"];
        $import_from_india = $searchdata[$i]["import_from_india"];
                          
     
        if(!$import_from_world)
        {                                                                       
            continue;                                                                                                                                                                                                                                                       
        }       

        $indiapercentage = $import_from_india ? ($import_from_india / $import_from_world) * 100 : 0 ;
        $worldpercentage = $indiapercentage ? 100 - $indiapercentage : 100;

        // Table rows                                                                                                                
        $rows .= "<tr>                                                                                                                 
            <td>".($i+1)."</td>                            
            <td>$hsncode</td>                     
            <td>$hsncode_name</td>
            <td>$import_to_country</td>
            <td class='hsn-header-blue'>".number_format($import_from_world, 0)."</td>
            <td class='hsn-header-yellow'>".number_format($import_from_india, 0)."</td>      
            <td class='hsn-header-yellow'>".round($indiapercentage, 2)."%</td>
        </tr>";

        // Push into arrays for Chart.js
        $hsnLabels[] = $hsncode;                                                                   
        $worldData[] = round($worldpercentage, 2);
        $indiaData[] = round($indiapercentage, 2);
    }   

    // ✅ Output Chart.js script with JSON encoded arrays                                                              
  $javascriptCode = '
<script>                  
    const hscondeLabels = ' . json_encode($hsnLabels) . ';
    const worldPercentageData = ' . json_encode($worldData) . ';
    const indiaPercentageData = ' . json_encode($indiaData) . ';
                         
    const chartInstance = new Chart(document.getElementById("Top25HSNCodelineChart"), {
        type: "line",             
        data: {
            labels: hscondeLabels,
            datasets: [
                {
                    label: "India Percentage",
                    data: indiaPercentageData,
                    borderColor: "rgba(255, 159, 64, 1)",      
                    backgroundColor: "rgba(255, 159, 64, 0.3)", 
                    fill: true,
                    tension: 0.3
                }, 
                {
                    label: "World Percentage",
                    data: worldPercentageData,
                    borderColor: "rgba(54, 162, 235, 1)",       
                    backgroundColor: "rgba(54, 162, 235, 0.3)", 
                    fill: true,
                    tension: 0.3
                }
            ]
        },
        options: {
            responsive: true,
            plugins: {
                title: {
                    display: true,
                    text: "India vs World Percentage by HSN Code"
                }
            },
            scales: {
                x: {
                    title: { display: true, text: "HSN Codes" }
                },
                y: {
                    title: { display: true, text: "Percentage" }
                }
            }
        }
    });

    // Hide World dataset by default
    chartInstance.setDatasetVisibility(1, false);
    chartInstance.update();
</script>
';


}

}
                                     
                                     
                                     
                                     
                                  
                                     
                                     
                                     

require_once(REQUIRED_PATH . 'header.php');
require_once(VIEWS_PATH . "top-25-hsn-code1.html");
require_once(REQUIRED_PATH . 'footer.php');

function getHsnCodeImage($chapter = '', $hsncode = '')
{  
    global $alltables;

    if ($chapter && $hsncode) {
        $wherecondition = "WHERE hscode = '$hsncode' && chapterno = '$chapter'";
    } else if ($chapter) {
        $wherecondition = " WHERE chapterno = '$chapter'";
    } else {
        $wherecondition = "WHERE hscode = '$hsncode'";
    }

    $sqlhsncodeimg = "SELECT chapterno,image FROM " . HSNCODE_IMAGE_TABLE . " $wherecondition LIMIT 0,4";


    $hsncodeImgData = $alltables->getInfo("", $sqlhsncodeimg);
    $hsncodeCount = count($hsncodeImgData);

    $base = DOC_ROOT . 'assets/img/hsn';

    if ($hsncodeCount) {
        for ($i = 0; $i < $hsncodeCount; $i++) {
            $chapterno = $hsncodeImgData[$i]['chapterno'];
            $imageval = $hsncodeImgData[$i]['image'];

            $imageurl =   $base . "/" . $chapterno . "/" . $imageval;

            $imagearray[$i] = $imageurl;
        }
    }

    return $imagearray;
}
function getHSNCodeChapter($selectChapterCode = '')
{
    $alltables = new AllTables();
    $sql = "SELECT DISTINCT Chapter FROM " . MAIN_IMPORT_TABLE . " WHERE Chapter > 0  ORDER BY Chapter ASC";
    $data = $alltables->getInfo("", $sql);
    $count = is_array($data) ? count($data) : 0;
   
    if ($count) {

        $options .= "<option value='' disabled> Select Chapter</option>";

        for ($i = 0; $i < $count; $i++) {
            $value = $data[$i]["Chapter"];

            if ($value == $selectChapterCode && $selectChapterCode > 0) {
                $options .= "<option value='" . $value . "' data-search='" . $value . "' selected>$value</option>";
            } else {
                $options .= "<option value='" . $value . "' data-search='" . $value . "'>$value</option>";
            }
        }
    }
    return $options;
}
function getHSNCode($chapter = '', $selectCode = '')
{
    $alltables = new AllTables();
    $wherecondition = '';
    if ($chapter) {
        $wherecondition = "WHERE Chapter = '$chapter' AND CHAR_LENGTH(HSNcode) > 6";
    } else {
        $wherecondition = "WHERE CHAR_LENGTH(HSNcode) > 6";
    }

    $sqlhsncode = "SELECT DISTINCT(HSNcode), name  FROM " . MAIN_IMPORT_TABLE . " $wherecondition ORDER BY HSNcode ASC";
    $hsncodedata = $alltables->getInfo("", $sqlhsncode);
    $hsncodecount = count($hsncodedata);
    if ($hsncodecount) {
        $hsncodeoptions .= "<option value=''> Select HSNCode </option>";

        for ($i = 0; $i < $hsncodecount; $i++) {
            $hsncode = $hsncodedata[$i]["HSNcode"];
            $name = $hsncodedata[$i]["name"];
            $value = $hsncode . "-" . $name;
            $code = $hsncode;

            if ($code == $selectCode && $selectCode > 0) {
                $hsncodeoptions .= "<option value='" . $code . "' data-search='" . $value . "' selected>$value</option>";
            } else {
                $hsncodeoptions .= "<option value='" . $code . "' data-search='" . $value . "'>$value</option>";
            }
        }
    }
    return $hsncodeoptions;
}
function getFromCountry($fromCountry = [])
{
    $alltables = new AllTables();
    $sqlimportfrom = "SELECT DISTINCT  import_from_country FROM " . MAIN_IMPORT_TABLE . ";";
    $sqlimportfromdata = $alltables->getInfo("", $sqlimportfrom);
    $importfromdatacount = count($sqlimportfromdata);
    if ($importfromdatacount) {
        $importfromoptions .= "<option value=''> Select Country</option>";

        if (!is_array($fromCountry)) {
            $fromCountry = []; // force it to be an array
        }
        for ($i = 0; $i < $importfromdatacount; $i++) {
            $importfrom = $sqlimportfromdata[$i]["import_from_country"];
            $selected = in_array($importfrom, $fromCountry) ? "selected" : "";
            $importfromoptions .= "<option value='$importfrom' $selected>$importfrom</option>";
        }
    }
    return $importfromoptions;
}
function getToCountry($to_country = '')
{
    $alltables = new AllTables();
    // $sqlimportto = "SELECT DISTINCT import_to_country FROM " .      MAIN_IMPORT_TABLE. " where import_to_country = 'USA'";  
    $sqlimportto = "SELECT DISTINCT import_to_country FROM " . MAIN_IMPORT_TABLE;
    $sqlimporttodata = $alltables->getInfo("", $sqlimportto);
    $sqlimporttodatacount = count($sqlimporttodata);

    if ($sqlimporttodatacount) {
        for ($i = 0; $i < $sqlimporttodatacount; $i++) {
            $importto = $sqlimporttodata[$i]["import_to_country"];

            if ($importto == $to_country) {
                $importtoptions .= "<option value='" . $importto . "' selected>$importto</option>";
            } else {

                $importtoptions .= "<option value='" . $importto . "'>$importto</option>";
            }
        }
    }
    return $importtoptions;
}


function getHSCodeName($hsncodename)
{
    $alltables = new AllTables();
    $value = '';
    $sqlhsncode = "SELECT DISTINCT(HSNcode), name FROM " . MAIN_IMPORT_TABLE . " WHERE HSNcode = '$hsncodename'";
    $hsncodedata = $alltables->getInfo("", $sqlhsncode);


    if (is_array($hsncodedata)) {
        $hsncode = $hsncodedata[0]["HSNcode"];
        $name = $hsncodedata[0]["name"];
        $value = $hsncode . "-" . $name;
    }

    return $value;
}
