<?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 value=''> 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($selectCode='')
{
    $alltables = new AllTables();
    // $sqlhsncode = "SELECT DISTINCT(HSNcode),name FROM " . MAIN_IMPORT_TABLE . " ORDER BY HSNcode ASC;";
    $sqlhsncode = "SELECT DISTINCT(HSNcode), name 
FROM " . MAIN_IMPORT_TABLE . " 
WHERE CHAR_LENGTH(HSNcode) > 6 
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 . ";";
    $sqlimporttodata = $alltables->getInfo("", $sqlimportto);
    $sqlimporttodatacount = count($sqlimporttodata);
    
    if ($sqlimporttodatacount) 
    {
        $importtoptions .= "<option value=''> Select Country</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 getTotalImportHSNCodeCount($data,$searchCountry)
{
        $total = 0;

    foreach ($searchCountry as $country) 
    {
        if ($country === 'WORLD' && isset($data[$country][0]['value_of_import']) && $data[$country][0]['value_of_import'] > 0) 
        {
            return $data[$country][0]['value_of_import'];
        } 
        elseif (isset($data[$country][0]['value_of_import'])) 
        {
            $total += $data[$country][0]['value_of_import'];
        }
    }
    return $total; 
}

function generatehtmlData($data,$searchCountry)
{
    $tddata = '';    
    $total = getTotalImportHSNCodeCount($data,$searchCountry);
    
    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;
                
                if($country == 'WORLD')
                {
                     $tddata .= "<td>".number_format($value,0)."</td>";
                }
                else
                {
                    $share_percentage = ($total > 0) ? ((100 * $value) / $total) : 0;
                    $tddata .= "<td> ".number_format($value,0)."</td>";
                    $tddata .= "<td>".number_format($share_percentage, 2)."%</td>";
                }
               
            }
        }  
        else                                                                               
        {
            $tddata .= "<td></td>";
            $tddata .= "<td></td>";
        }
    }
    return $tddata;
}

function generateHeader($defaultCountry,$fromCountry)
{
    $years = ['2021','2022','2023'];
    $colspancount = (count($defaultCountry)*2)-1;
    $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)
        {
            if($country == 'WORLD')
            {
                $theadTwo .= "<th>Import from $country  to  $fromCountry</th>";
            }
            else
            {
                $theadTwo .= "<th>Import from $country  to  $fromCountry</th>";
                $theadTwo .= "<th>$country share in $year%</th>";
            }
           
        }
    }           
    $theadOne .="</tr>";                   
    $theadTwo .="</tr>";   
    return $theadOne.$theadTwo;
}

if (isset($_REQUEST['hsn_code'])||isset($_REQUEST['chapeter_code'])) 
{
    $hsn_code          = sanitize(($_REQUEST['hsn_code']??''), SQL + HTML);
    $to_country          = sanitize(($_POST['to_country']??'USA'), SQL + HTML);
    $chaptercode          = intval($_REQUEST['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, FIELD(import_from_country, 'WORLD', 'INDIA', 'CHINA','VIETNAM') $orderby";
    }
       
    // echo $searchsql;    
    $searchdata = $alltables->getInfo("", $searchsql);   
    $searchdatacount = count($searchdata);
    if ($searchdatacount==0)
    {
        // $searchsql = "SELECT * FROM " . MAIN_IMPORT_TABLE . " $wherecondition ORDER BY year_of_import,HSNcode ASC, FIELD(import_from_country, 'WORLD', 'INDIA', 'CHINA','VIETNAM') $orderby";
    }
    // 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
            ];
        } 
        
        
        // PIE CHART - Focusing on 2023 data only
$pieLabels = [];
$pieValues = [];
$pieBackgroundColors = [];
$pieBorderColors = [];

$colorMap = [
    '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)'],
];

$totalValue = 0;
foreach ($graphData as $country => $yearlyData) {
    $value = $yearlyData['2023'] ?? 0;
    $totalValue += $value;
}

// Now calculate percentage and format labels
foreach ($graphData as $country => $yearlyData) {
    $value = $yearlyData['2023'] ?? 0;
    $percent = $totalValue ? round(($value / $totalValue) * 100, 1) : 0;
    $pieLabels[] = ucfirst(strtolower($country)) . " ({$percent}%)";
    $pieValues[] = $value;
    $pieBackgroundColors[] = $colorMap[$country][0];
    $pieBorderColors[] = $colorMap[$country][1];
}

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