<?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);

$color = array(
    'WORLD' => 'hsn-header-blue',
    "INDIA" => 'hsn-header-yellow',
    "CHINA" => 'hsn-header-white',
    "VIETNAM" => 'hsn-header-green'
);

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 generateHeader($defaultCountry, $fromCountry)
{
    global $color;
    $years = ['2021', '2022', '2023'];


    if (FIX_COUNTRY == true) {
        $defaultCountry = array();

        $defaultFixCountry = array('WORLD', 'INDIA', 'CHINA', 'VIETNAM');

        $defaultCountry = array_filter($defaultFixCountry, function ($value) use ($fromCountry) {
            return $value !== $fromCountry;
        });
    }


    $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) {
            $tdColorClass = $color[$country];

            if ($country == 'WORLD') {
                $theadTwo .= "<th class='$tdColorClass'>Import from $country  to  $fromCountry</th>";
            } else {
                $theadTwo .= "<th class='$tdColorClass' >Import from $country  to  $fromCountry</th>";
                $theadTwo .= "<th class='$tdColorClass' >$country share in $year%</th>";
            }
        }
    }
    $theadOne .= "</tr>";
    $theadTwo .= "</tr>";
    return $theadOne . $theadTwo;
}

function generatehtmlData($data, $searchCountryArray, $to_country)
{
    global $color;
    $tddata = '';


    if (FIX_COUNTRY == true) {
        $searchCountryArray = array();

        $defaultFixCountry = array('WORLD', 'INDIA', 'CHINA', 'VIETNAM');

        $searchCountryArray = array_filter($defaultFixCountry, function ($value) use ($to_country) {
            return $value !== $to_country;
        });
    }



    $total = getTotalImportHSNCodeCount($data, $searchCountryArray);


    foreach ($searchCountryArray as $country) {

        $tdColorClass = $color[$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'] : 'N/A';

                if ($country == 'WORLD') {
                    if ($value > 0) {
                        $tddata .= "<td class='$tdColorClass'>" . number_format($value, 0) . "</td>";
                    } else {

                        $tddata .= "<td class='$tdColorClass'> N/A </td>";
                    }
                } else {
                    if ($value > 0) {
                        $share_percentage = ($total > 0) ? ((100 * $value) / $total) : 0;
                        $tddata .= "<td class='$tdColorClass'> " . number_format($value, 0) . "</td>";
                        $tddata .= "<td class='$tdColorClass'>" . number_format($share_percentage, 2) . "%</td>";
                    } else {
                        $tddata .= "<td class='$tdColorClass'> N/A </td>";
                        $tddata .= "<td class='$tdColorClass'> N/A </td>";
                    }
                }
            }
        } else {
            if ($country == 'WORLD') {
                $tddata .= "<td> N/A </td>";
            } else {
                $tddata .= "<td>  N/A </td>";
                $tddata .= "<td>  N/A </td>";
            }
        }
    }
    return $tddata;
}


if (isset($_REQUEST['hsn_code']) || isset($_REQUEST['chapeter_code'])) {
    $hsn_code          = sanitize($_REQUEST['hsn_code'], SQL + HTML);
    $to_country          = sanitize($_REQUEST['to_country'], SQL + HTML);
    $chaptercode          = intval($_REQUEST['chapeter_code']);
    // $to_country = 'USA';               

    // $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]."'";
    // }

    $where = [];
    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;


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

    foreach ($where as $key => $value) {
        if ($i == 0) {
            $i++;

            if ($key == 'import_from_country') {
                $wherecondition .= " WHERE $key in ($value) ";
                $orderby = " , FIELD(import_from_country, " . $from_country . ")";
            } else if ($key == 'HSNcode') {
                $hscode_string = strval($value);
                $hscode_length = strlen($hscode_string);

                $hsn_imagecode = substr($hscode_string, 0, 4);

                if ($hscode_length <= MAX_STRING) {
                    $newwherecondition .= " WHERE $key LIKE '$value%'";
                }

                $wherecondition .= " WHERE $key  = '$value' ";
            } else {
                $wherecondition .= " WHERE $key = '$value' ";
                $newwherecondition .= " WHERE $key = '$value' ";
            }
        } else {
            if ($key == 'import_from_country') {
                $wherecondition .= " AND $key in ($value) ";
                $orderby = " , FIELD(import_from_country, " . $from_country . ")";
            } else if ($key == 'HSNcode') {
                $hscode_string = strval($value);
                $hscode_length = strlen($hscode_string);
                $hsn_imagecode = substr($hscode_string, 0, 4);

                if ($hscode_length <= MAX_STRING) {
                    $newwherecondition .= " AND $key LIKE '$value%'";
                }

                $wherecondition .= " AND $key  = '$value'";
            } else {
                $wherecondition .= " AND $key = '$value' ";
                $newwherecondition .= " AND $key = '$value' ";
            }
        }
    }



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

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

    if ($hsn_code) {
        $searchText .= " HSNCode :  " . getHSCodeName($hsn_code) . ",";
    }


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


    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";
    }

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

    if ((!$searchdatacount) && $newwherecondition) {
        $searchsql = "SELECT * FROM " . MAIN_IMPORT_TABLE . " $newwherecondition ORDER BY year_of_import,HSNcode ASC, FIELD(import_from_country, 'WORLD', 'INDIA', 'CHINA','VIETNAM') $orderby";
        $searchdata = $alltables->getInfo("", $searchsql);
        $searchdatacount = count($searchdata);
    }



    if (FIX_COUNTRY == true) {
        $defaultFixCountry = array('WORLD', 'INDIA', 'CHINA', 'VIETNAM');
        $allowedCountries = array_filter($defaultFixCountry, function ($value) use ($to_country) {
            return $value !== $to_country;
        });
    }

    // Prepare structured array
    $organizedData = [];
    if ($searchdatacount) {
        $imagearray = getHsnCodeImage($chaptercode, $hsn_imagecode);

        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];




            if (!in_array($import_from_country, $searchCountry)) {
                $searchCountry[] = $import_from_country;
            }


            // Initialize graph data for all countries in allowedCountries
            foreach ($allowedCountries as $country) {
                // Ensure every country has at least 0 for this year
                if (!isset($graphData[$country][$year_of_import])) {
                    $graphData[$country][$year_of_import] = 0;
                }

                // Only add value if the current record matches this country
                if ($import_from_country == $country) {
                    $graphData[$country][$year_of_import] += $value_of_import;
                }
            }
        }


        $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, $to_country);
            }
            $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
            ];
        }




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

        // Step 1: Calculate average value for each country
        $averages = [];
        $totalValue = 0;

        foreach ($graphData as $country => $yearlyData) {
            $sum = 0;
            $count = 0;

            foreach ($allYears as $year) {
                if (isset($yearlyData[$year])) {
                    $sum += $yearlyData[$year];
                    $count++;
                }
            }

            $avg = $count ? $sum / $count : 0;
            $averages[$country] = $avg;
            $totalValue += $avg;         
        }

        // Step 2: Prepare data for pie chart
        foreach ($averages as $country => $avgValue) {
            $percent = $totalValue ? round(($avgValue / $totalValue) * 100, 1) : 0;
            $pieLabels[] = ucfirst(strtolower($country)) . " ({$percent}%)";
            $pieValues[] = $avgValue;
            $pieBackgroundColors[] = $colorMap[$country][0] ?? 'rgba(200,200,200,0.7)';
            $pieBorderColors[] = $colorMap[$country][1] ?? 'rgba(200,200,200,1)';
        }
    }
}
                                     

require_once(REQUIRED_PATH . 'header.php');
require_once(VIEWS_PATH . "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='all'> 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='' hidden> 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) {
        $importtoptions .= "<option value='' hidden> 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 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;
}
