<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/aipma2025/include/config.php");
require_once(INCLUDE_PATH . "startup.php");
$alltables = new AllTables();
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> Select Chapter</option>';
        for ($i = 0; $i < $count; $i++)             
        {
            $value = $data[$i]["Chapter"];
            $selected = in_array($value, $selectChapterCode) ? "selected" : "";
            $options .= "<option value='$value' $selected>$value</option>"; 
        }
    }
    return $options;
}
function getHSNCode($selectCode='')
{
    $alltables = new AllTables();
    $sqlhsncode = "SELECT DISTINCT(HSNcode),name FROM " . MAIN_IMPORT_TABLE . " ORDER BY HSNcode ASC;";
    $hsncodedata = $alltables->getInfo("", $sqlhsncode);
    $hsncodecount = count($hsncodedata);
    if ($hsncodecount) 
    {                 
        for ($i = 0; $i <= $hsncodecount; $i++)                                         
        {
            $hsncode = $hsncodedata[$i]["HSNcode"];          
            $name = $hsncodedata[$i]["name"];
            $value = $hsncode."-".$name;    
            $code = $hsncode;
            if($code == $selectCode)
            {
                $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></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 . ";";
    $sqlimporttodata = $alltables->getInfo("", $sqlimportto);
    $sqlimporttodatacount = count($sqlimporttodata);
    if ($sqlimporttodatacount) 
    {
        $importtoptions .= '<option></option>';
        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 generatehtmlData($data,$searchCountry)
{
    $tddata = '';    
    foreach($searchCountry as $country)                                                                                   
    {
        if (isset($data[$country]) && is_array($data[$country])) 
        {
            $importdata = $data[$country];
            $count = count($importdata);
            for ($i = 0; $i < $count; $i++) 
            {
                $value = isset($importdata[$i]['value_of_import']) ? $importdata[$i]['value_of_import'] : 0;
                $tddata .= "<td>$value</td>";
            }
        }  
        else                                                                               
        {
            $tddata .= "<td></td>";
        }
    }
    return $tddata;
}    
function generateHeader($defaultCountry,$fromCountry)
{
    $years = ['2021','2022','2023'];
    $colspancount = count($defaultCountry);
    $theadOne .='<tr> <th rowspan="2" class="align-middle">Sr. No.</th>
                    <th rowspan="2" class="align-middle">HSN Product Code</th>
                    <th rowspan="2" class="align-middle">Product Label</th>';
    $theadTwo .="<tr>";                   
    foreach($years as $year)
    {
        $theadOne .= "<th colspan='".$colspancount."'>Value in US $ (".$year.")</th>";
        foreach($defaultCountry as $country)
        {
            $theadTwo .= "<th>Import from $country  to  $fromCountry</th>";
        }
    }           
    $theadOne .="</tr>";                   
    $theadTwo .="</tr>";   
    return $theadOne.$theadTwo;
}
if (isset($_POST['btnsearch'])) {
    $hsn_code          = sanitize($_POST['hsn_code'], SQL + HTML);
    $to_country          = sanitize($_POST['to_country'], SQL + HTML);
    $chaptercode          = intval($_POST['chapeter_code']);
    // $from_country_arr          = sanitize($_POST['from_country'], SQL + HTML);
    // if (count($from_country_arr) > 1) 
    // {
    //     $from_country = "'" . implode("','", $from_country_arr) . "'";
    // } 
    // else if(count($from_country_arr)) 
    // {
    //     $from_country = "'".$from_country_arr[0]."'";
    // }
    empty($hsn_code)            ? null : $where['HSNcode'] = $hsn_code;
    empty($to_country)          ? null : $where['import_to_country'] = $to_country;
    empty($from_country)        ? null : $where['import_from_country'] = $from_country;
    empty($chaptercode)         ? null : $where['Chapter'] = $chaptercode;
    foreach($where as $key => $value)
    {
        if($i == 0)
        {
            $i=1;
            if($key == 'import_from_country')
            {
                $wherecondition .= " WHERE $key in ($value) ";
                $orderby = " , FIELD(import_from_country, ".$from_country.")";
            }
            else
            {
                $wherecondition .= " WHERE $key = '$value' ";
            }
        }                                                                               
        else
        {
            if($key == 'import_from_country')
            {
                $wherecondition .= " AND $key in ($value) ";
                $orderby = " , FIELD(import_from_country, ".$from_country.")";
            }
            else
            {
                $wherecondition .= " AND $key = '$value' ";
            }       
        }
    }
    if($wherecondition)
    {
        $searchsql = "SELECT * FROM " . MAIN_IMPORT_TABLE . " $wherecondition ORDER BY year_of_import,HSNcode ASC $orderby";
    }
    echo  $searchsql;                                                                                                                                                                                      
    $searchdata = $alltables->getInfo("", $searchsql);   
    $searchdatacount = count($searchdata);
    // Prepare structured array
    $organizedData = [];        
    if ($searchdatacount) 
    {  
        for ($i = 0; $i < $searchdatacount; $i++) 
        {                                                                   
            $id                   = $searchdata[$i]["ID"];    
            $hsncode              = $searchdata[$i]["HSNcode"];                                 
            $productname          = $searchdata[$i]["name"];
            $import_from_country  = $searchdata[$i]["import_from_country"];
            $import_to_country    = strtoupper($searchdata[$i]["import_to_country"]);
            $year_of_import       = $searchdata[$i]["year_of_import"];         
            $value_of_import      = $searchdata[$i]["value_of_import"];                     
            $organizedData[$hsncode]['productname'] = $productname;
            $organizedData[$hsncode]['data'][$year_of_import][$import_from_country][] = $searchdata[$i];
            $graphData[$import_from_country][$year_of_import] += $value_of_import ;
            // ✅ Add unique country only
            if (!in_array($import_from_country, $searchCountry)) {
                $searchCountry[] = $import_from_country;
            }
         }    
         $header = (generateHeader($searchCountry,$to_country));                      
        $counter = 1;
        foreach($organizedData as $HSNCodes => $HSNCodesData)                                                                              
        {                                               
            $hsncode = $HSNCodes;                                 
            $productname = $HSNCodesData['productname'];                                       
            $row .= " <tr>                                                           
                        <td>$counter</td>
                        <td>$hsncode</td>
                        <td> $productname</td>";
               foreach($HSNCodesData['data'] as $years => $yearsData)
               {
                    $row .= generatehtmlData($yearsData,$searchCountry);
                }  
            $counter++;
            $row .= " </tr> ";
        }                                         
        // Bar Graph Varaible
        // Pugin Text
        // Define consistent years
        $allYears = ['2021', '2022', '2023']; // or extract dynamically if needed
        $colors = [
            'INDIA' => ['rgba(75, 192, 192, 0.7)', 'rgba(75, 192, 192, 1)'],
            'CHINA' => ['rgba(255, 99, 132, 0.7)', 'rgba(255, 99, 132, 1)'],
            'VIETNAM' => ['rgba(54, 162, 235, 0.7)', 'rgba(54, 162, 235, 1)'],
            'WORLD' => ['rgba(153, 102, 255, 0.7)', 'rgba(153, 102, 255, 1)'],
        ];
        $jsDatasets = [];                                                         
        foreach ($graphData as $country => $yearlyData) {
            $dataPoints = [];       
            foreach ($allYears as $year) {              
                $dataPoints[] = $yearlyData[$year] ?? 0;
            }
            $bg = $colors[$country][0];
            $border = $colors[$country][1];
            $jsDatasets[] = [
                'label' => ucfirst(strtolower($country)),
                'data' => $dataPoints,
                'backgroundColor' => $bg,
                'borderColor' => $border,
                'borderWidth' => 1
            ];
        }    
    }
}   
require_once(REQUIRED_PATH . 'header.php'); 
require_once(VIEWS_PATH . "hsn-code1.html");
require_once(REQUIRED_PATH . 'footer.php');
