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

                
define('CHAPTER_SUMMARY_VIEW','chapter_world_india_2023_summary');

$chapterLabels = [];
$worldData = []; 
$indiaData = [];


$chapterTitlenNames = array(
    '39' => 'All Plastic Finished Products',
    '56'=>'Wadding, felt and nonwovens; special yarns; twine, cordage, ropes and cables and articles thereof',
    '63' => 'Other made-up textile articles, Sacks, Bags, Tarpaulins',
    '85' => 'Electrical machinery and equipment and parts thereof',
    '87' => 'Vehicles other than railway or tramway rolling stock, and parts and accessories thereof',
    '90' => 'Optical, photographic, cinematographic, measuring, checking, precision, medical or surgical ',
    '94' => 'Furniture; bedding, mattresses, mattress supports, cushions and similar stuffed furnishings ',
    '95' => 'Toys, games and sports requisites; parts and accessories thereof',
    '96' => 'Miscellaneous manufactured articles',
);


if (isset($_REQUEST['to_country'])) 
{
    $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,";
    }

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


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

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


    if ($searchdatacount) 
    {
        
        $displayCountryName = ucfirst(strtolower($to_country));
        // Table header
        $rowheader .= "
        <tr>
            <th class='align-middle'>Sr. No.</th>
            <th class='align-middle'>Chapter</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++) 
        {
            $chapter = $searchdata[$i]["chapter"];
            $import_to_country = $searchdata[$i]["import_to_country"];
            $import_from_world= $searchdata[$i]["total_world_import"];
            $import_from_india = $searchdata[$i]["total_india_import"];
                              
         
            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>$chapter</td>                     
                <td>".$chapterTitlenNames[$chapter]."</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
            $chapterLabels[] = $chapter;                                                                   
            $worldData[] = round($worldpercentage, 2);
            $indiaData[] = round($indiapercentage, 2);
        }   
    
        // ✅ Output Chart.js script with JSON encoded arrays                                                              
      $javascriptCode = '
    <script>                  
        const chapterLabels = ' . json_encode($chapterLabels) . ';
        const worldPercentageData = ' . json_encode($worldData) . ';
        const indiaPercentageData = ' . json_encode($indiaData) . ';
                             
        const chartInstance = new Chart(document.getElementById("Top25HSNCodelineChart"), {
            type: "line",             
            data: {
                labels: chapterLabels,
                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 Chapter"
                    }
                },
                scales: {
                    x: {
                        title: { display: true, text: "Chapter" }
                    },
                    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 . "chapter-summary1.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 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;
}

