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੐)|#o0aڱ$I>}k&1`U#V?YsV x>{t1[I~D&(I$I/{H0fw"q"y%4 IXyE~M3 8XψL}qE$I[> nD?~sf ]o΁ cT6"?'_Ἣ $I>~.f|'!N?⟩0G KkXZE]ޡ;/&?k OۘH$IRۀwXӨ<7@PnS04aӶp.:@\IWQJ6sS%I$e5ڑv`3:x';wq_vpgHyXZ 3gЂ7{{EuԹn±}$I$8t;b|591nءQ"P6O5i }iR̈́%Q̄p!I䮢]O{H$IRϻ9s֧ a=`- aB\X0"+5"C1Hb?߮3x3&gşggl_hZ^,`5?ߎvĸ%̀M!OZC2#0x LJ0 Gw$I$I}<{Eb+y;iI,`ܚF:5ܛA8-O-|8K7s|#Z8a&><a&/VtbtLʌI$I$I$I$I$I$IRjDD%tEXtdate:create2022-05-31T04:40:26+00:00!Î%tEXtdate:modify2022-05-31T04:40:26+00:00|{2IENDB`Mini Shell

HOME


Mini Shell 1.0
DIR:/home/costmasters.in/www/application/modules/frontend/views/graph/
Upload File :
Current File : /home/costmasters.in/www/application/modules/frontend/views/graph/show.php
<?php
// print_r($week_date); 
// echo"<br>";
// print_r($week_price_one); 
// echo"<br>";
// print_r($week_price_two); 
// die;
$SelectedStart = $start;
$SelectedEnd = $end;

// Determine the number of records dynamically
$dataSets = [
    "Week" => $week_price_one,
    "Month" => $month_price_one,
    "Year" => $year_price_one,
    "Quarter" => $quarterly_price_one,
    "Default" => $price_one
];

$sessionWeeksd = $this->session->userdata('weeksd') ?: 'Day'; // Default to 'Day' if missing
$num_record = isset($dataSets[$sessionWeeksd]) ? count($dataSets[$sessionWeeksd]) : count($price_one);


// Set figure style based on $commodityTwo
$figureStyle = ($commodityTwo === '') ? 'position: static; bottom: 0;' : 'position: absolute; bottom: 0;';

/**
 * Function to align datasets by date
 */
function alignDataByDate($dataOne, $dataTwo, $dateKey, $valueKey)
{
    $dataOneMapped = array_column($dataOne, $valueKey, $dateKey);
    $dataTwoMapped = array_column($dataTwo, $valueKey, $dateKey);

    $allDates = array_unique(array_merge(array_keys($dataOneMapped), array_keys($dataTwoMapped)));
    sort($allDates);

    foreach ($allDates as $date) {
        $dataOneMapped[$date] = $dataOneMapped[$date] ?? null;
        $dataTwoMapped[$date] = $dataTwoMapped[$date] ?? null;
    }

    ksort($dataOneMapped);
    ksort($dataTwoMapped);

    return [$dataOneMapped, $dataTwoMapped];
}

// Align data for different timeframes
list($Week_price_one, $Week_price_two) = (count($week_price_one) !== count($week_price_two))
    ? alignDataByDate($week_price_one, $week_price_two, 'chart_date', 'chart_item_cost2')
    : [array_column($week_price_one, 'chart_item_cost2', 'chart_date'), array_column($week_price_two, 'chart_item_cost2', 'chart_date')];
// print_r(alignDataByDate($year_price_one, $year_price_two, 'chart_date', 'chart_item_cost2'));
// echo "<br>";
// print_r([
//     array_column($year_price_one, 'chart_item_cost2', 'chart_date'),
//     array_column($year_price_two, 'chart_item_cost2', 'chart_date')
// ]);
// echo "<br>";
// echo "<pre>";
// print_r($Week_price_one);
// echo "<pre>";
// foreach ($week_date as $week) {
//     echo "</pre>";

//     print_r($week['chart_date']); 
//     echo "<br>";
//  // Now prints the last date of each week (Sunday)
//     echo "</pre>";

// }
// echo "</pre>";
// die;
// print_r($Week_price_two);
// echo "<br>";
// echo "<pre>";
// print_r([$Week_price_one, $Week_price_two]);
// echo "</pre>";

 // die;
list($Month_price_one, $Month_price_two) = (count($month_price_one) !== count($month_price_two))
    ? alignDataByDate($month_price_one, $month_price_two, 'chart_date', 'chart_item_cost2')
    : [array_column($month_price_one, 'chart_item_cost2', 'chart_date'), array_column($month_price_two, 'chart_item_cost2', 'chart_date')];

list($Year_price_one, $Year_price_two) = (count($year_price_one) !== count($year_price_two))
    ? alignDataByDate($year_price_one, $year_price_two, 'chart_date', 'chart_item_cost2')
    : [array_column($year_price_one, 'chart_item_cost2', 'chart_date'), array_column($year_price_two, 'chart_item_cost2', 'chart_date')];

list($Quarterly_price_one, $Quarterly_price_two) = (count($quarterly_price_one) !== count($quarterly_price_two))
    ? alignDataByDate($quarterly_price_one, $quarterly_price_two, 'chart_date', 'chart_item_cost2')
    : [array_column($quarterly_price_one, 'chart_item_cost2', 'chart_date'), array_column($quarterly_price_two, 'chart_item_cost2', 'chart_date')];

list($Price_one, $Price_two) = (count($price_one) !== count($price_two))
    ? alignDataByDate($price_one, $price_two, 'chart_date', 'item_cost')
    : [array_column($price_one, 'item_cost', 'chart_date'), array_column($price_two, 'item_cost', 'chart_date')];

// ----------------------------------------------------------------------------
// HELPER FUNCTIONS
// ----------------------------------------------------------------------------

/**
 * Calculate the percentage difference between the first and last values.
 */
function calculate_percent($first, $last) {
    $difference = $first - $last;
    return ($first > 0) ? ($difference / $first) * 100 : 0;
}

/**
 * Retrieve start and end values from the provided start/end data.
 * 
 * @param array  $start_data Data for start value (expects an 'avg_cost' field).
 * @param array  $end_data   Data for end value.
 * @param array  $arr        The price data array.
 * @param string $field      The field to use for end data formatting (default: 'chart_item_cost2').
 * @return array An array with keys 'start' and 'end'.
 */
function get_start_end($start_data, $end_data, $arr, $field = 'chart_item_cost2') {
    $start = 0.0;
    $end   = 0.0;

    if (!empty($start_data) && !empty($start_data['avg_cost'])) {
        $starts = explode(',', $start_data['avg_cost']);
        $start  = $starts[0];
    }

    if (!empty($end_data)) {
        foreach ($end_data as $en) {
            // Use the provided field; default to 0 if not set.
            $ends = number_format($en[$field] ?? 0, 1);
            // In your original logic, $end was set to the first value of $arr.
            $end = $arr[0][$field] ?? 0;
        }
    }

    return compact('start', 'end');
}

/**
 * Process chart data for Week, Month, Year, or Quarter.
 *
 * @param array  $price_data The price data array.
 * @param array  $start_date The start date data.
 * @param array  $end_date   The end date data.
 * @param array  $min_data   The min/max/avg data (an array of arrays).
 * @param string $field      The field name for the price value (default: 'chart_item_cost2').
 *
 * @return array The calculated values.
 */
function process_chart_data($price_data, $start_date, $end_date, $min_data, $field = 'chart_item_cost2') {
    // Get the first and last price values.
    $arr = $price_data;
    $first_arr = floatval(str_replace(",", "", number_format($arr[0][$field] ?? 0, 1)));
    $last_arr  = floatval(str_replace(",", "", number_format($arr[count($arr) - 1][$field] ?? 0, 1)));

    // Get start and end values.
    $start_end = get_start_end($start_date, $end_date, $arr, $field);
    $start = $start_end['start'];
    $end   = $start_end['end'];

    // Calculate overall difference and percentage.
    $difference = $first_arr - $last_arr;
    $percent    = calculate_percent($first_arr, $last_arr);

    // Get min, max, and avg values.
    // If $min_data is a list of arrays, use its first element.
    $first_min_data = !empty($min_data) ? reset($min_data) : null;
    if ($first_min_data === null) {
         $min_cost = 1;
         $max_cost = 1;
         $avg_cost = 1;
    } else {
         $min_cost = $first_min_data['min_cost'] ?? 0;
         $max_cost = $first_min_data['max_cost'] ?? 0;
         $avg_cost = $first_min_data['avg_cost'] ?? 0;
    }

    // Calculate differences.
    $diff_min     = $first_arr - $min_cost;
    $diff_min_max = $first_arr - $max_cost;
    $diff_avg     = $first_arr - $avg_cost;

    // Calculate percentage differences.
    $percent_min     = ($first_arr > 0) ? ($diff_min / $first_arr) * 100 : 0;
    $percent_min_max = ($first_arr > 0) ? ($diff_min_max / $first_arr) * 100 : 0;
    $percent_avg     = ($first_arr > 0) ? ($diff_avg / $first_arr) * 100 : 0;

    // For display purposes.
    $min = $min_cost;
    $max = $max_cost;
    $avg = $avg_cost;

    return compact(
         'first_arr', 'last_arr', 'start', 'end', 'difference', 'percent',
         'min', 'max', 'avg', 'diff_min', 'diff_min_max', 'diff_avg',
         'percent_min', 'percent_min_max', 'percent_avg'
    );
}

/**
 * Process analysis price data (when the field names differ).
 * 
 * This function uses "item_cost" for prices rather than "chart_item_cost2".
 *
 * @param array $price_data The price data (e.g., $price_one).
 * @param array $end_data   The end date data (expects field 'chart_item_cost').
 * @param array $row        A single row from the $analysis array containing min/max/avg.
 *
 * @return array The calculated values.
 */
function process_analysis_data($price_data, $end_data, $row) {
    // Use the 'item_cost' field.
    $arr = $price_data;
    $first_arr = floatval(str_replace(",", "", number_format($arr[0]['item_cost'] ?? 0, 1)));
    $last_arr  = floatval(str_replace(",", "", number_format($arr[count($arr) - 1]['item_cost'] ?? 0, 1)));

    // For analysis, extract the start value directly from the row.
    $temp = explode(',', $row['item_cost'] ?? '');
    $start = $temp[0] ?? 0;

    $end = 0.0;
    if (!empty($end_data)) {
        foreach ($end_data as $en) {
            $ends = number_format($en['chart_item_cost'] ?? 0, 1);
            $end = $ends;
        }
    }

    $difference = $first_arr - $last_arr;
    $percent    = ($first_arr > 0) ? ($difference / $first_arr) * 100 : 0;

    // Get min, max, and avg values from the analysis row.
    $min = $row['min_cost'] ?? 0;
    $max = $row['max_cost'] ?? 0;
    $avg = $row['avg_cost'] ?? 0;

    $diff_min     = $first_arr - $min;
    $diff_min_max = $first_arr - $max;
    $diff_avg     = $first_arr - $avg;

    $percent_min     = ($first_arr > 0) ? ($diff_min / $first_arr) * 100 : 0;
    $percent_min_max = ($first_arr > 0) ? ($diff_min_max / $first_arr) * 100 : 0;
    $percent_avg     = ($first_arr > 0) ? ($diff_avg / $first_arr) * 100 : 0;

    return compact(
        'first_arr', 'last_arr', 'start', 'end', 'difference', 'percent',
        'min', 'max', 'avg', 'diff_min', 'diff_min_max', 'diff_avg',
        'percent_min', 'percent_min_max', 'percent_avg'
    );
}

$cy_data = [
    ['label' => 'Month Var.', 'avg' => 'current_month_avg', 'diff' => 'month_price_difference', 'perc' => 'month_price_percentage'],
    ['label' => 'Year Avg.', 'avg' => 'current_year_avg', 'diff' => 'average_price_difference', 'perc' => 'average_price_percentage'],
    ['label' => 'Year Min.', 'avg' => 'current_year_min', 'diff' => 'min_price_difference', 'perc' => 'min_price_percentage'],
    ['label' => 'Year Max.', 'avg' => 'current_year_max', 'diff' => 'max_price_difference', 'perc' => 'max_price_percentage']
];

?>
<style>
.text-danger { color: #f30a0a !important; }
.text-success { color: #06892e !important; }
.select2-container--default.select2-container--disabled .select2-selection--single {
    background: #fff !important;
    border-color: #e4e8ee !important;
}
.apexcharts-canvas { margin-top: -10px;}
.apexcharts-title-text { margin-bottom: -20px; }
#commodity, #commodity_head, #commodityTwo { width: 100% !important;}
.note-sec { <?php echo $figureStyle; ?> }
</style>

<?php if ($subs_type[0]['t_and_c'] == 'true') { ?>
<!-- begin:: Content -->
<div class="kt-container  kt-container--fluid  kt-grid__item kt-grid__item--fluid cs_main_ktportal" style="margin-top:30px"> <!--begin::Portlet-->
    <div class="kt-portlet">
        <div class="kt-portlet__body">
            <!--begin::Section-->
            <div class="kt-section">
                <div class="kt-section__content">
                      <?php if (($commodity != '' || $commodityTwo != '') && (!empty($num_record) && $num_record > 0)) { ?>
                        <div class="row">
                            <div class="col-sm-12 col-md-12 col-lg-3 left">
                                <?php if (!in_array($subs_type[0]['subscription_type'], PDF_ACCESS)) { ?>
                                <div class="graph-show">
                                    <?php if (in_array($subs_type[0]['subscription_type'], ONLINE_CUSTOM_PARTIAL_ACCESS)) {?>
                                        <?php
                                            $num_record = $difference = $percent = 0;
                                            $avg_diff = $avg_percent = $percent_min_max = $diff_min_max = $percent_min = $diff_min = 0;
                                            // Determine the number of records based on the session's time period (weeksd)
                                            switch ($this->session->userdata('weeksd')) {
                                                case "Week":
                                                    $num_record = count($week_price_one);
                                                    break;
                                                case "Month":
                                                    $num_record = count($month_price_one);
                                                    break;
                                                case "Year":
                                                    $num_record = count($year_price_one);
                                                    break;
                                                case "Quarter":
                                                    $num_record = count($quarterly_price_one);
                                                    break;
                                                default:
                                                    $num_record = count($price_one);
                                            }
                                        ?>                                      
                                        <div class="card custom-card">
                                            <div class="card-body">
                                                <div id="analysisTable">
                                                    <?php if ($commodity != '' && $commodityTwo != '') { ?>
                                                    <h4 style="font-size: 1em; font-weight: 600; color: #0083c5; margin: 0 0 5px;">Analysis: <?php echo $commodity; ?></h4>
                                                    <div class="table-responsive">
                                                        <table class="table table-bordered table-analysis">
                                                            <!-- add style to make it bold as other heading by rajdeep kaur 30-03-2024 -->
                                                               <div class="analysis_sub_text">
                                                                 <p>Selection Period</p>
                                                               </div>
                                                            <thead>
                                                                <tr>
                                                                    <th></th>
                                                                    <th>Price</th>
                                                                    <th>Difference</th>
                                                                    <th>%age</th>
                                                                </tr>
                                                            </thead>
                                                            <tbody>
                                                                <?php
                                                                    if ($this->session->userdata('weeksd') == "Week") {
                                                                        foreach ($week_price_one as $row) {
                                                                            if (!empty($row['chart_date'])) {
                                                                                // Process weekly data using field 'chart_item_cost2'
                                                                                $chart_data = process_chart_data($week_price_one, $week_start_date, $week_end_date, $week_min, 'chart_item_cost2');
                                                                                // (Break if only one result is needed.)
                                                                            }
                                                                        }
                                                                    } else if ($this->session->userdata('weeksd') == "Month") {
                                                                        foreach ($month_price_one as $row) {
                                                                            if (!empty($row['chart_date'])) {
                                                                                $chart_data = process_chart_data($month_price_one, $month_start_date, $month_end_date, $month_min, 'chart_item_cost2');
                                                                            }
                                                                        }
                                                                    } else if ($this->session->userdata('weeksd') == "Year") {
                                                                        foreach ($year_price_one as $row) {
                                                                            if (!empty($row['chart_date'])) {
                                                                                $chart_data = process_chart_data($year_price_one, $year_start_date, $year_end_date, $year_min, 'chart_item_cost2');
                                                                            }
                                                                        }
                                                                    } else if ($this->session->userdata('weeksd') == "Quarter") {
                                                                        foreach ($quarterly_price_one as $row) {
                                                                            if (!empty($row['chart_date'])) {
                                                                                $chart_data = process_chart_data($quarterly_price_one, $quarterly_start_date, $quarterly_end_date, $quarterly_min, 'chart_item_cost2');
                                                                            }
                                                                        }
                                                                    } else {
                                                                        foreach ($analysis as $row) {
                                                                            if (!empty($row['chart_date'])) {
                                                                                $chart_data = process_analysis_data($price_one, $end_date, $row);
                                                                            }
                                                                        }
                                                                    }
                                                                    // Extract these variables for use in the display section.
                                                                    extract($chart_data);
                                                                    // Check if form has been submitted and necessary data is available.
                                                                    $isValid = isset($_POST['commodity_head']) && $num_record > 0;
                                                                ?>                                          
                                                                 <!-- Start Section -->
                                                                <tr>
                                                                    <td>Start</td>
                                                                    <td><input type="text" name="" value="<?php echo $isValid ? $first_arr : '0.0'; ?>" readonly /></td>
                                                                    <td><input type="text" name="" value="" readonly /></td>
                                                                    <td><input type="text" name="" value="" readonly /></td>
                                                                </tr>
                                                                <!-- End Section -->
                                                                <tr>
                                                                    <td>End</td>
                                                                    <td><input type="text" name="" value="<?php echo $isValid ? $last_arr : '0.0'; ?>" readonly /></td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php
                                                                            $arrow_icon = $difference < 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                            $text_color = $difference < 0 ? 'text-danger' : 'text-success';
                                                                            ?>
                                                                            <i class="fa <?php echo $arrow_icon; ?> <?php echo $text_color; ?>"></i>
                                                                            <input type="text" class="<?php echo $text_color; ?>" name=""
                                                                                   value="<?php echo $isValid ? sprintf("%.1f", $difference) : '0.0'; ?>" readonly />
                                                                        </div>
                                                                    </td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php
                                                                            $arrow_icon = $percent < 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                            $text_color = $percent < 0 ? 'text-danger' : 'text-success';
                                                                            ?>
                                                                            <i class="fa <?php echo $arrow_icon; ?> <?php echo $text_color; ?>"></i>
                                                                            <input type="text" class="<?php echo $text_color; ?>" name=""
                                                                                   value="<?php echo $isValid ? sprintf("%.1f", $percent) : '0.0'; ?>" readonly />
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                                <!-- Min Section -->
                                                                <tr>
                                                                    <td>Min</td>
                                                                    <td><input type="text" name="" value="<?php echo $isValid ? sprintf("%.1f", $min) : '0.0'; ?>" readonly /></td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php
                                                                            $arrow_icon = $diff_min < 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                            $text_color = $diff_min < 0 ? 'text-danger' : 'text-success';
                                                                            ?>
                                                                            <i class="fa <?php echo $arrow_icon; ?> <?php echo $text_color; ?>"></i>
                                                                            <input type="text" class="<?php echo $text_color; ?>" name=""
                                                                                   value="<?php echo $isValid ? sprintf("%.1f", $diff_min) : '0.0'; ?>" readonly />
                                                                        </div>
                                                                    </td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php
                                                                            $arrow_icon = $percent_min < 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                            $text_color = $percent_min < 0 ? 'text-danger' : 'text-success';
                                                                            ?>
                                                                            <i class="fa <?php echo $arrow_icon; ?> <?php echo $text_color; ?>"></i>
                                                                            <input type="text" class="<?php echo $text_color; ?>" name=""
                                                                                   value="<?php echo $isValid ? sprintf("%.1f", $percent_min) : '0.0'; ?>" readonly />
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                                <!-- Max Section -->
                                                                <tr>
                                                                    <td>Max</td>
                                                                    <td><input type="text" name="" value="<?php echo $isValid ? sprintf("%.1f", $max) : '0.0'; ?>" readonly /></td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php
                                                                            $arrow_icon = $diff_min_max < 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                            $text_color = $diff_min_max < 0 ? 'text-danger' : 'text-success';
                                                                            ?>
                                                                            <i class="fa <?php echo $arrow_icon; ?> <?php echo $text_color; ?>"></i>
                                                                            <input type="text" class="<?php echo $text_color; ?>" name=""
                                                                                   value="<?php echo $isValid ? sprintf("%.1f", $diff_min_max) : '0.0'; ?>" readonly />
                                                                        </div>
                                                                    </td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php
                                                                            $arrow_icon = $percent_min_max < 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                            $text_color = $percent_min_max < 0 ? 'text-danger' : 'text-success';
                                                                            ?>
                                                                            <i class="fa <?php echo $arrow_icon; ?> <?php echo $text_color; ?>"></i>
                                                                            <input type="text" class="<?php echo $text_color; ?>" name=""
                                                                                   value="<?php echo $isValid ? sprintf("%.1f", $percent_min_max) : '0.0'; ?>" readonly />
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                                <!-- Avg Section -->
                                                                <tr>
                                                                    <td>Avg</td>
                                                                    <td><input type="text" name="" value="<?php echo $isValid ? sprintf("%.1f", $avg) : '0.0'; ?>" readonly /></td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php
                                                                            $arrow_icon = $diff_avg < 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                            $text_color = $diff_avg < 0 ? 'text-danger' : 'text-success';
                                                                            ?>
                                                                            <i class="fa <?php echo $arrow_icon; ?> <?php echo $text_color; ?>"></i>
                                                                            <input type="text" class="<?php echo $text_color; ?>" name=""
                                                                                   value="<?php echo $isValid ? sprintf("%.1f", $diff_avg) : '0.0'; ?>" readonly />
                                                                        </div>
                                                                    </td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php
                                                                            $arrow_icon = $percent_avg < 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                            $text_color = $percent_avg < 0 ? 'text-danger' : 'text-success';
                                                                            ?>
                                                                            <i class="fa <?php echo $arrow_icon; ?> <?php echo $text_color; ?>"></i>
                                                                            <input type="text" class="<?php echo $text_color; ?>" name=""
                                                                                   value="<?php echo $isValid ? sprintf("%.1f", $percent_avg) : '0.0'; ?>" readonly />
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                    <div class="table-responsive">
                                                        <table class="table table-bordered table-analysis">
                                                            <!-- Heading Section -->
                                                            <div class="analysis_sub_text">
                                                                <p>CY Quick View w.r.t "To Date"</p>
                                                            </div>
                                                            <thead>
                                                                <tr>
                                                                    <th></th>
                                                                    <th>Price</th>
                                                                    <th>Difference</th>
                                                                    <th>%age</th>
                                                                </tr>
                                                            </thead>
                                                            <tbody>
                                                                <?php
                                                                foreach ($cy_data as $item):
                                                                    $avg = isset($current_year_data[$item['avg']]) ? $current_year_data[$item['avg']] : '0.0';
                                                                    $diff = isset($current_year_data[$item['diff']]) ? $current_year_data[$item['diff']] : '0.0';
                                                                    $perc = isset($current_year_data[$item['perc']]) ? $current_year_data[$item['perc']] : '0.0';
                                                                    $diff_arrow = $diff < 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                    $diff_color = $diff < 0 ? 'text-danger' : 'text-success';
                                                                    $perc_arrow = $perc < 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                    $perc_color = $perc < 0 ? 'text-danger' : 'text-success';
                                                                ?>
                                                                <tr>
                                                                    <td><?php echo $item['label']; ?></td>
                                                                    <td>
                                                                        <input type="text" value="<?php echo $avg; ?>" readonly />
                                                                    </td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <i class="fa <?php echo $diff_arrow; ?> <?php echo $diff_color; ?>"></i>
                                                                            <input type="text" class="<?php echo $diff_color; ?>" value="<?php echo sprintf("%.1f", $diff); ?>" readonly />
                                                                        </div>
                                                                    </td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <i class="fa <?php echo $perc_arrow; ?> <?php echo $perc_color; ?>"></i>
                                                                            <input type="text" class="<?php echo $perc_color; ?>" value="<?php echo sprintf("%.1f", $perc); ?>" readonly />
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                                <?php endforeach; ?>
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                    <div class="row cs_margin_chart">
                                                        <!-- First Chart Section -->
                                                        <div class="cs_view_chart">
                                                            <button class="open-modal-btn">
                                                                <img src="<?= base_url() ?>/assets/frontend/images/chart_zoom.png" alt="Zoom Chart">
                                                            </button>
                                                            <div id="modal1" class="modal">
                                                                <div class="modal-content">
                                                                    <span class="close">&times;</span>
                                                                    <div id="myChartPUP"></div>
                                                                </div>
                                                            </div>
                                                            <div id="myChart"></div>
                                                        </div>
                                                        
                                                        <!-- Second Chart Section -->
                                                        <div class="cs_view_chart">
                                                            <button class="open-modal-btn">
                                                                <img src="<?= base_url() ?>/assets/frontend/images/chart_zoom.png" alt="Zoom Chart">
                                                            </button>
                                                            <div id="modal2" class="modal">
                                                                <div class="modal-content">
                                                                    <span class="close">&times;</span>
                                                                    <div id="myChart1PUP"></div>
                                                                </div>
                                                            </div>
                                                            <div id="myChart1"></div>
                                                        </div>
                                                    </div>
                                                 <hr style="border-color: #000;border-width: 2px;">
                                                  <h4 style="font-size: 1em; font-weight: 600; color: #0083c5; margin: 0 0 
                                                    5px;">Analysis: <?php echo $commodityTwo; ?></h4>
                                                    <div class="table-responsive">
                                                        <table class="table table-bordered table-analysis">
                                                        <div class="analysis_sub_text"><p>Selection Period</p></div>                                             
                                                            <thead>
                                                                <tr>
                                                                    <th></th>
                                                                    <th>Price</th>
                                                                    <th>Difference</th>
                                                                    <th>%age</th>
                                                                </tr>
                                                            </thead>
                                                            <tbody>
                                                                <?php
                                                                    // Process price data for Commodity Two ("price_two") using helper functions
                                                                    if ($this->session->userdata('weeksd') == "Week") {
                                                                        foreach ($week_price_two as $row) {
                                                                            if (!empty($row['chart_date'])) {
                                                                                $chart_data2 = process_chart_data(
                                                                                    $week_price_two,      // price data array for week (commodity two)
                                                                                    $week_start_date2,    // start date data for week (commodity two)
                                                                                    $week_end_date2,      // end date data for week (commodity two)
                                                                                    $week_min2,           // min/max/avg data for week (commodity two)
                                                                                    'chart_item_cost2'    // field name for the cost value
                                                                                );
                                                                                break; // Stop once a valid record is processed.
                                                                            }
                                                                        }
                                                                    } else if ($this->session->userdata('weeksd') == "Month") {
                                                                        foreach ($month_price_two as $row) {
                                                                            if (!empty($row['chart_date'])) {
                                                                                $chart_data2 = process_chart_data(
                                                                                    $month_price_two,
                                                                                    $month_start_date2,
                                                                                    $month_end_date2,
                                                                                    $month_min2,
                                                                                    'chart_item_cost2'
                                                                                );
                                                                                break;
                                                                            }
                                                                        }
                                                                    } else if ($this->session->userdata('weeksd') == "Year") {
                                                                        foreach ($year_price_two as $row) {
                                                                            if (!empty($row['chart_date'])) {
                                                                                $chart_data2 = process_chart_data(
                                                                                    $year_price_two,
                                                                                    $year_start_date2,
                                                                                    $year_end_date2,
                                                                                    $year_min2,
                                                                                    'chart_item_cost2'
                                                                                );
                                                                                break;
                                                                            }
                                                                        }
                                                                    } else if ($this->session->userdata('weeksd') == "Quarter") {
                                                                        foreach ($quarterly_price_two as $row) {
                                                                            if (!empty($row['chart_date'])) {
                                                                                $chart_data2 = process_chart_data(
                                                                                    $quarterly_price_two,
                                                                                    $quarterly_start_date2,
                                                                                    $quarterly_end_date2,
                                                                                    $quarterly_min2,
                                                                                    'chart_item_cost2'
                                                                                );
                                                                                break;
                                                                            }
                                                                        }
                                                                    } else {
                                                                        // Default: Analysis Price Logic (using different field names for commodity two)
                                                                        foreach ($analysis2 as $row) {
                                                                            if (!empty($row['chart_date'])) {
                                                                                $chart_data2 = process_analysis_data(
                                                                                    $price_two,  // price data array for analysis (commodity two)
                                                                                    $end_date2,  // end date data for analysis (commodity two)
                                                                                    $row         // a single analysis row containing min/max/avg values
                                                                                );
                                                                                break;
                                                                            }
                                                                        }
                                                                    }

                                                                    // Now, $chart_data2 contains the computed values for commodity two.
                                                                    // Extract the values so they can be used directly in your display code.
                                                                    extract($chart_data2);
                                                                ?>
                                                                <tr>
                                                                    <td>Start</td>
                                                                    <td>
                                                                        <input type="text" name="" 
                                                                               value="<?= (isset($_POST['commodity_head']) && $num_record > 0 && isset($first_arr)) ? $first_arr : '0.0'; ?>" 
                                                                               readonly />
                                                                    </td>
                                                                    <td><input type="text" name="" value="" readonly /></td>
                                                                    <td><input type="text" name="" value="" readonly /></td>
                                                                </tr>
                                                                <tr>
                                                                    <td>End</td>
                                                                    <td>
                                                                        <input type="text" name="" 
                                                                               value="<?= (isset($_POST['commodity_head']) && $num_record > 0 && isset($last_arr)) ? $last_arr : '0.0'; ?>" 
                                                                               readonly />
                                                                    </td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php 
                                                                                $arrow_icon = ($difference < 0) ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                                $text_color = ($difference < 0) ? 'text-danger' : 'text-success';
                                                                            ?>
                                                                            <i class="fa <?= $arrow_icon ?> <?= $text_color ?>"></i>
                                                                            <input type="text" class="<?= $text_color ?>" name=""
                                                                                   value="<?= (isset($_POST['commodity_head']) && $num_record > 0) ? sprintf('%.1f', $difference) : '0.0'; ?>" 
                                                                                   readonly />
                                                                        </div>
                                                                    </td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php 
                                                                                $arrow_icon = ($percent < 0) ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                                $text_color = ($percent < 0) ? 'text-danger' : 'text-success';
                                                                            ?>
                                                                            <i class="fa <?= $arrow_icon ?> <?= $text_color ?>"></i>
                                                                            <input type="text" class="<?= $text_color ?>" name=""
                                                                                   value="<?= (isset($_POST['commodity_head']) && $num_record > 0) ? sprintf('%.1f', $percent) : '0.0'; ?>" 
                                                                                   readonly />
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td>Min</td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <input type="text" name="" 
                                                                                   value="<?= (isset($_POST['commodity_head']) && $num_record > 0) ? sprintf('%.1f', $min) : '0.0'; ?>" 
                                                                                   readonly />
                                                                        </div>
                                                                    </td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php 
                                                                                $arrow_icon = ($diff_min < 0) ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                                $text_color = ($diff_min < 0) ? 'text-danger' : 'text-success';
                                                                            ?>
                                                                            <i class="fa <?= $arrow_icon ?> <?= $text_color ?>"></i>
                                                                            <input type="text" class="<?= $text_color ?>" name=""
                                                                                   value="<?= (isset($_POST['commodity_head']) && $num_record > 0) ? sprintf('%.1f', $diff_min) : '0.0'; ?>" 
                                                                                   readonly />
                                                                        </div>
                                                                    </td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php 
                                                                                $arrow_icon = ($percent_min < 0) ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                                $text_color = ($percent_min < 0) ? 'text-danger' : 'text-success';
                                                                            ?>
                                                                            <i class="fa <?= $arrow_icon ?> <?= $text_color ?>"></i>
                                                                            <input type="text" class="<?= $text_color ?>" name=""
                                                                                   value="<?= (isset($_POST['commodity_head']) && $num_record > 0) ? sprintf('%.1f', $percent_min) : '0.0'; ?>" 
                                                                                   readonly />
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td>Max</td>
                                                                    <td>
                                                                        <input type="text" name=""
                                                                               value="<?= (isset($_POST['commodity_head']) && $num_record > 0) ? sprintf('%.1f', $max) : '0.0'; ?>" 
                                                                               readonly />
                                                                    </td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php 
                                                                                $arrow_icon = ($diff_min_max < 0) ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                                $text_color = ($diff_min_max < 0) ? 'text-danger' : 'text-success';
                                                                            ?>
                                                                            <i class="fa <?= $arrow_icon ?> <?= $text_color ?>"></i>
                                                                            <input type="text" class="<?= $text_color ?>" name=""
                                                                                   value="<?= (isset($_POST['commodity_head']) && $num_record > 0) ? sprintf('%.1f', $diff_min_max) : '0.0'; ?>" 
                                                                                   readonly />
                                                                        </div>
                                                                    </td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php 
                                                                                $arrow_icon = ($percent_min_max < 0) ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                                $text_color = ($percent_min_max < 0) ? 'text-danger' : 'text-success';
                                                                            ?>
                                                                            <i class="fa <?= $arrow_icon ?> <?= $text_color ?>"></i>
                                                                            <input type="text" class="<?= $text_color ?>" name=""
                                                                                   value="<?= (isset($_POST['commodity_head']) && $num_record > 0) ? sprintf('%.1f', $percent_min_max) : '0.0'; ?>" 
                                                                                   readonly />
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td>Avg</td>
                                                                    <td>
                                                                        <input type="text" name=""
                                                                               value="<?= isset($_POST["commodity_head"]) && $num_record > 0
                                                                                   ? sprintf("%.1f", $avg)
                                                                                   : "0.0" ?>" 
                                                                               readonly />
                                                                    </td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php
                                                                            $arrow_icon = $diff_avg < 0 ? "fa-arrow-up" : "fa-arrow-down";
                                                                            $text_color = $diff_avg < 0 ? "text-danger" : "text-success";
                                                                            ?>
                                                                            <i class="fa <?= $arrow_icon ?> <?= $text_color ?>"></i>
                                                                            <input type="text" class="<?= $text_color ?>" name=""
                                                                                   value="<?= isset($_POST["commodity_head"]) && $num_record > 0
                                                                                       ? sprintf("%.1f", $diff_avg)
                                                                                       : "0.0" ?>" 
                                                                                   readonly />
                                                                        </div>
                                                                    </td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php
                                                                            $arrow_icon = $percent_avg < 0 ? "fa-arrow-up" : "fa-arrow-down";
                                                                            $text_color = $percent_avg < 0 ? "text-danger" : "text-success";
                                                                            ?>
                                                                            <i class="fa <?= $arrow_icon ?> <?= $text_color ?>"></i>
                                                                            <input type="text" class="<?= $text_color ?>" name=""
                                                                                   value="<?= isset($_POST["commodity_head"]) && $num_record > 0
                                                                                       ? sprintf("%.1f", $percent_avg)
                                                                                       : "0.0" ?>" 
                                                                                   readonly />
                                                                        </div>
                                                                    </td>
                                                                </tr>

                                                            </tbody>
                                                        </table>
                                                    </div>
                                                    <div class="table-responsive">
                                                        <table class="table table-bordered table-analysis">
                                                            <!-- Heading Section -->
                                                            <div class="analysis_sub_text">
                                                                <p>CY Quick View w.r.t "To Date"</p>
                                                            </div>
                                                            <thead>
                                                                <tr>
                                                                    <th></th>
                                                                    <th>Price</th>
                                                                    <th>Difference</th>
                                                                    <th>%age</th>
                                                                </tr>
                                                            </thead>
                                                            <tbody>
                                                                <?php
                                                                foreach ($cy_data as $item):
                                                                    $avg = isset($current_year_data2[$item['avg']]) ? $current_year_data2[$item['avg']] : '0.0';
                                                                    $diff = isset($current_year_data2[$item['diff']]) ? $current_year_data2[$item['diff']] : '0.0';
                                                                    $perc = isset($current_year_data2[$item['perc']]) ? $current_year_data2[$item['perc']] : '0.0';
                                                                    $diff_arrow = $diff < 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                    $diff_color = $diff < 0 ? 'text-danger' : 'text-success';
                                                                    $perc_arrow = $perc < 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                    $perc_color = $perc < 0 ? 'text-danger' : 'text-success';
                                                                ?>
                                                                <tr>
                                                                    <td><?php echo $item['label']; ?></td>
                                                                    <td>
                                                                        <input type="text" value="<?php echo $avg; ?>" readonly />
                                                                    </td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <i class="fa <?php echo $diff_arrow; ?> <?php echo $diff_color; ?>"></i>
                                                                            <input type="text" class="<?php echo $diff_color; ?>" value="<?php echo sprintf("%.1f", $diff); ?>" readonly />
                                                                        </div>
                                                                    </td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <i class="fa <?php echo $perc_arrow; ?> <?php echo $perc_color; ?>"></i>
                                                                            <input type="text" class="<?php echo $perc_color; ?>" value="<?php echo sprintf("%.1f", $perc); ?>" readonly />
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                                <?php endforeach; ?>
                                                            </tbody>                                                 
                                                        </table>
                                                    </div>
                                                    <div class="row" style="height:190px;">
                                                        <div class="cs_view_chart">
                                                            <button class="open-modal-btn" data-target="#modalMonth"><img
                                                                    src="<?php echo base_url()?>/assets/frontend/images/chart_zoom.png"></button>
                                                            <div id="modalMonth" class="modal">
                                                                <div class="modal-content">
                                                                    <span class="close">&times;</span>
                                                                    <div id="myChartMonthCommodityTwoPUP"></div>
                                                                </div>
                                                            </div>
                                                            <div id="myChartMonthCommodityTwo"></div>
                                                        </div>
                                                        <div class="cs_view_chart">
                                                            <button class="open-modal-btn" data-target="#modalYear"><img
                                                                    src="<?php echo base_url()?>/assets/frontend/images/chart_zoom.png"></button>
                                                            <div id="modalYear" class="modal">
                                                                <div class="modal-content">
                                                                    <span class="close">&times;</span>
                                                                    <div id="myChartYearCommodityTwoPUP"></div>
                                                                </div>
                                                            </div>
                                                            <div id="myChartYearCommodityTwo"></div>
                                                        </div>
                                                    </div>
                                                    <?php
                                                 } else {
                                                ?>
                                                <?php if (isset($_POST['commodity_head']) && ($num_record > 0)) {?>
                                                    <!-- it represent  single  commodity data on dashboard-->                                            
                                                    <h4 style="font-size: 1em; font-weight: 600; color: #0083c5; margin: 0 0 5px;">Analysis</h4>
                                                    <div class="table-responsive">
                                                        <table class="table table-bordered table-analysis">
                                                           <div class="analysis_sub_text"><p>Selection Period</p></div>
                                                            <thead>
                                                                <tr>
                                                                    <th></th>
                                                                    <th>Price</th>
                                                                    <th>Difference</th>
                                                                    <th>%age</th>
                                                                </tr>
                                                            </thead>
                                                            <tbody>
                                                                <?php
                                                                   if ($this->session->userdata('weeksd') == "Week") {
                                                                        foreach ($week_price_one as $row) {
                                                                            if (!empty($row['chart_date'])) {
                                                                                // Process weekly data using field 'chart_item_cost2'
                                                                                $chart_data = process_chart_data($week_price_one, $week_start_date, $week_end_date, $week_min, 'chart_item_cost2');
                                                                                // (Break if only one result is needed.)
                                                                            }
                                                                        }
                                                                    } else if ($this->session->userdata('weeksd') == "Month") {
                                                                        foreach ($month_price_one as $row) {
                                                                            if (!empty($row['chart_date'])) {
                                                                                $chart_data = process_chart_data($month_price_one, $month_start_date, $month_end_date, $month_min, 'chart_item_cost2');
                                                                            }
                                                                        }
                                                                    } else if ($this->session->userdata('weeksd') == "Year") {
                                                                        foreach ($year_price_one as $row) {
                                                                            if (!empty($row['chart_date'])) {
                                                                                $chart_data = process_chart_data($year_price_one, $year_start_date, $year_end_date, $year_min, 'chart_item_cost2');
                                                                            }
                                                                        }
                                                                    } else if ($this->session->userdata('weeksd') == "Quarter") {
                                                                        foreach ($quarterly_price_one as $row) {
                                                                            if (!empty($row['chart_date'])) {
                                                                                $chart_data = process_chart_data($quarterly_price_one, $quarterly_start_date, $quarterly_end_date, $quarterly_min, 'chart_item_cost2');
                                                                            }
                                                                        }
                                                                    } else {
                                                                        // Default: Analysis Price Logic (uses different field names)
                                                                        foreach ($analysis as $row) {
                                                                            if (!empty($row['chart_date'])) {
                                                                                $chart_data = process_analysis_data($price_one, $end_date, $row);
                                                                            }
                                                                        }
                                                                    }
                                                                    // Extract these variables for use in the display section.
                                                                    extract($chart_data);
                                                                    // Check if form has been submitted and necessary data is available.
                                                                    $isValid = isset($_POST['commodity_head']) && $num_record > 0;
                                                                ?>
                                                                <!-- Start Section -->
                                                                <tr>
                                                                    <td>Start</td>
                                                                    <td><input type="text" name="" value="<?php echo $isValid ? $first_arr : '0.0'; ?>" readonly /></td>
                                                                    <td><input type="text" name="" value="" readonly /></td>
                                                                    <td><input type="text" name="" value="" readonly /></td>
                                                                </tr>

                                                                <!-- End Section -->
                                                                <tr>
                                                                    <td>End</td>
                                                                    <td><input type="text" name="" value="<?php echo $isValid ? $last_arr : '0.0'; ?>" readonly /></td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php
                                                                            $arrow_icon = $difference < 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                            $text_color = $difference < 0 ? 'text-danger' : 'text-success';
                                                                            ?>
                                                                            <i class="fa <?php echo $arrow_icon; ?> <?php echo $text_color; ?>"></i>
                                                                            <input type="text" class="<?php echo $text_color; ?>" name=""
                                                                                   value="<?php echo $isValid ? sprintf("%.1f", $difference) : '0.0'; ?>" readonly />
                                                                        </div>
                                                                    </td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php
                                                                            $arrow_icon = $percent < 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                            $text_color = $percent < 0 ? 'text-danger' : 'text-success';
                                                                            ?>
                                                                            <i class="fa <?php echo $arrow_icon; ?> <?php echo $text_color; ?>"></i>
                                                                            <input type="text" class="<?php echo $text_color; ?>" name=""
                                                                                   value="<?php echo $isValid ? sprintf("%.1f", $percent) : '0.0'; ?>" readonly />
                                                                        </div>
                                                                    </td>
                                                                </tr>

                                                                <!-- Min Section -->
                                                                <tr>
                                                                    <td>Min</td>
                                                                    <td><input type="text" name="" value="<?php echo $isValid ? sprintf("%.1f", $min) : '0.0'; ?>" readonly /></td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php
                                                                            $arrow_icon = $diff_min < 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                            $text_color = $diff_min < 0 ? 'text-danger' : 'text-success';
                                                                            ?>
                                                                            <i class="fa <?php echo $arrow_icon; ?> <?php echo $text_color; ?>"></i>
                                                                            <input type="text" class="<?php echo $text_color; ?>" name=""
                                                                                   value="<?php echo $isValid ? sprintf("%.1f", $diff_min) : '0.0'; ?>" readonly />
                                                                        </div>
                                                                    </td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php
                                                                            $arrow_icon = $percent_min < 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                            $text_color = $percent_min < 0 ? 'text-danger' : 'text-success';
                                                                            ?>
                                                                            <i class="fa <?php echo $arrow_icon; ?> <?php echo $text_color; ?>"></i>
                                                                            <input type="text" class="<?php echo $text_color; ?>" name=""
                                                                                   value="<?php echo $isValid ? sprintf("%.1f", $percent_min) : '0.0'; ?>" readonly />
                                                                        </div>
                                                                    </td>
                                                                </tr>

                                                                <!-- Max Section -->
                                                                <tr>
                                                                    <td>Max</td>
                                                                    <td><input type="text" name="" value="<?php echo $isValid ? sprintf("%.1f", $max) : '0.0'; ?>" readonly /></td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php
                                                                            $arrow_icon = $diff_min_max < 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                            $text_color = $diff_min_max < 0 ? 'text-danger' : 'text-success';
                                                                            ?>
                                                                            <i class="fa <?php echo $arrow_icon; ?> <?php echo $text_color; ?>"></i>
                                                                            <input type="text" class="<?php echo $text_color; ?>" name=""
                                                                                   value="<?php echo $isValid ? sprintf("%.1f", $diff_min_max) : '0.0'; ?>" readonly />
                                                                        </div>
                                                                    </td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php
                                                                            $arrow_icon = $percent_min_max < 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                            $text_color = $percent_min_max < 0 ? 'text-danger' : 'text-success';
                                                                            ?>
                                                                            <i class="fa <?php echo $arrow_icon; ?> <?php echo $text_color; ?>"></i>
                                                                            <input type="text" class="<?php echo $text_color; ?>" name=""
                                                                                   value="<?php echo $isValid ? sprintf("%.1f", $percent_min_max) : '0.0'; ?>" readonly />
                                                                        </div>
                                                                    </td>
                                                                </tr>

                                                                <!-- Avg Section -->
                                                                <tr>
                                                                    <td>Avg</td>
                                                                    <td><input type="text" name="" value="<?php echo $isValid ? sprintf("%.1f", $avg) : '0.0'; ?>" readonly /></td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php
                                                                            $arrow_icon = $diff_avg < 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                            $text_color = $diff_avg < 0 ? 'text-danger' : 'text-success';
                                                                            ?>
                                                                            <i class="fa <?php echo $arrow_icon; ?> <?php echo $text_color; ?>"></i>
                                                                            <input type="text" class="<?php echo $text_color; ?>" name=""
                                                                                   value="<?php echo $isValid ? sprintf("%.1f", $diff_avg) : '0.0'; ?>" readonly />
                                                                        </div>
                                                                    </td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <?php
                                                                            $arrow_icon = $percent_avg < 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                            $text_color = $percent_avg < 0 ? 'text-danger' : 'text-success';
                                                                            ?>
                                                                            <i class="fa <?php echo $arrow_icon; ?> <?php echo $text_color; ?>"></i>
                                                                            <input type="text" class="<?php echo $text_color; ?>" name=""
                                                                                   value="<?php echo $isValid ? sprintf("%.1f", $percent_avg) : '0.0'; ?>" readonly />
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                      <div class="table-responsive">
                                                        <table class="table table-bordered table-analysis">
                                                           <div class="analysis_sub_text"><p>CY Quick View w.r.t "To Date"</p></div>
                                                            <thead>
                                                                <tr>
                                                                    <th></th>
                                                                    <th>Price</th>
                                                                    <th>Difference</th>
                                                                    <th>%age</th>
                                                                </tr>
                                                            </thead>
                                                            <tbody>
                                                                <?php
                                                                foreach ($cy_data as $item):
                                                                    $avg = isset($current_year_data[$item['avg']]) ? $current_year_data[$item['avg']] : '0.0';
                                                                    $diff = isset($current_year_data[$item['diff']]) ? $current_year_data[$item['diff']] : '0.0';
                                                                    $perc = isset($current_year_data[$item['perc']]) ? $current_year_data[$item['perc']] : '0.0';
                                                                    $diff_arrow = $diff < 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                    $diff_color = $diff < 0 ? 'text-danger' : 'text-success';
                                                                    $perc_arrow = $perc < 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                                                                    $perc_color = $perc < 0 ? 'text-danger' : 'text-success';
                                                                ?>
                                                                <tr>
                                                                    <td><?php echo $item['label']; ?></td>
                                                                    <td>
                                                                        <input type="text" value="<?php echo $avg; ?>" readonly />
                                                                    </td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <i class="fa <?php echo $diff_arrow; ?> <?php echo $diff_color; ?>"></i>
                                                                            <input type="text" class="<?php echo $diff_color; ?>" value="<?php echo sprintf("%.1f", $diff); ?>" readonly />
                                                                        </div>
                                                                    </td>
                                                                    <td>
                                                                        <div class="d-sm-flex text-end">
                                                                            <i class="fa <?php echo $perc_arrow; ?> <?php echo $perc_color; ?>"></i>
                                                                            <input type="text" class="<?php echo $perc_color; ?>" value="<?php echo sprintf("%.1f", $perc); ?>" readonly />
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                                <?php endforeach; ?>
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                    <div class="row cs_margin_chart_single">
                                                        <div class="cs_view_chart">
                                                            <button class="open-modal-btn"><img
                                                                    src="<?php echo base_url()?>/assets/frontend/images/chart_zoom.png"></button>
                                                            <div id="modal" class="modal">
                                                                <div class="modal-content">
                                                                    <span class="close">&times;</span>
                                                                    <div id="myChartPUP">
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <div id="myChart">
                                                            </div>
                                                        </div>
                                                        <div class="cs_view_chart">
                                                            <button class="open-modal-btn"><img
                                                                    src="<?php echo base_url()?>/assets/frontend/images/chart_zoom.png"></button>
                                                            <div id="modal" class="modal">
                                                                <div class="modal-content">
                                                                    <span class="close">&times;</span>
                                                                    <div id="myChart1PUP">
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <div id="myChart1">
                                                            </div>
                                                        </div>
                                                    </div>
                                                <?php
                                                }
                                                ?>
                                                <?php
                                                }
                                                ?>
                                                </div>
                                            </div>
                                        </div>              
                                </div>
                                    <?php } ?>
                            </div>
                        <?php } } ?>

                            <!-- new design implementation with functionality by rajdeep kaur 27-04-2024 -->
                            <div class="col-sm-12 col-md-12 col-lg-9 right" style="padding-left:0;">
                                <div class="comodity_box">
                                    <div class="comodity_box_flex_btn">
                                        <form action="<?= base_url('graph/show') ?>" class="editor-graph" method="POST">
                                            <div class="comodity_part">
                                                <!-- Conditional check for partial subscription access graph view -->
                                              <?php
                                                function renderCommodityDropdown($categories, $selected_head, $allowed_ids = []){
                                                    ?>
                                                    <div class="cs_list">
                                                        <select name="commodity_head" id="commodity_head" class="form-control select2">
                                                            <option value="">Commodity Head</option>
                                                            <?php foreach ($categories as $cat):
                                                                if (empty($allowed_ids) || in_array($cat['id'], $allowed_ids)): ?>
                                                                    <option value="<?= $cat['category_name'] ?>" <?= ($selected_head == $cat['category_name']) ? 'selected' : '' ?>>
                                                                        <?= $cat['category_name'] ?>
                                                                    </option>
                                                                <?php endif;
                                                            endforeach; ?>
                                                        </select>
                                                    </div>
                                                    <?php
                                                }

                                                $selected_head = $this->session->userdata('commodity_head');
                                                $allowed_items = explode(',', $subs_type[0]['choose_type'] ?? ''); // Avoid undefined index errors

                                                if (in_array($subs_type[0]['subscription_type'], PARTIAL_ACCESS)) {
                                                    renderCommodityDropdown($cat_fetch_partial, $selected_head, $allowed_items);
                                                } elseif (in_array($subs_type[0]['subscription_type'], CUSTOM_ACCESS)) {
                                                    renderCommodityDropdown($cat_id, $selected_head, $allowed_items);
                                                } else {
                                                    renderCommodityDropdown($cat_id, $selected_head); // Show all items
                                                }
                                                ?>
                                                <!-- Commodity and comparison commodity dropdowns -->
                                                <div class="cs_list">
                                                    <select name="commodity" id="commodity" class="form-control commodity commodity2" data-live-search="true">
                                                        <option value="">Commodity</option>
                                                    </select>
                                                </div>
                                                <div class="cs_list">
                                                    <select name="commodityTwo" id="commodityTwo" class="form-control commodity">
                                                        <option value="">Comparison Commodity</option>
                                                    </select>
                                                </div>

                                                <!-- Date selection fields -->
                                                <div class="cs_list">
                                                    <input type="date" name="date_from" id="date_from" class="form-control cs_fonts" value="<?= $SelectedStart; ?>">
                                                </div>
                                                <div class="cs_list">
                                                    <input type="date" name="date_to" id="date_to" class="form-control cs_fonts" value="<?= $SelectedEnd; ?>">
                                                </div>

                                                <!-- Hidden input for weeks/months -->
                                                <input type="hidden" name="weekss" id="weekss_hidden" value="<?= $this->session->userdata('weeksd') ?: 'Month' ?>">

                                                <!-- Submit button -->
                                                <div class="cs_submit cs_sublist">
                                                    <button type="submit" name="submit" class="btn costmaster-button change-button" style="height: 32px;">Submit</button>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                    <div class="custom_icon_all col-md-12  d-flex justify-content-between align-items-center mt-1">
                                        <div class="custom_date_selection d-flex justify-content-start align-items-center gap-1">
                                            <div class="days_selections d-flex justify-content-start">
                                                <?php
                                                // Calculate YTD start and end dates
                                                $ytd_from = date("Y-01-01");
                                                $ytd_to   = date("Y-m-d");

                                                // Define time periods with corresponding offsets and labels
                                                $timePeriods = [
                                                    ['value' => '1_months', 'label' => '1 M', 'date_from' => '-1 month', 'date_to' => 'now'],
                                                    ['value' => '3_months', 'label' => '3 M', 'date_from' => '-3 month', 'date_to' => 'now'],
                                                    ['value' => '6_months', 'label' => '6 M', 'date_from' => '-6 month', 'date_to' => 'now'],
                                                    ['value' => '9_months', 'label' => '9 M', 'date_from' => '-9 month', 'date_to' => 'now'],
                                                    ['value' => '1_ytd',    'label' => 'YTD', 'date_from' => $ytd_from, 'date_to' => $ytd_to],
                                                    ['value' => '1_year',   'label' => '1 Y', 'date_from' => '-1 year', 'date_to' => 'now']
                                                ];

                                                // Loop through each time period and create a form dynamically.
                                                // Note: We use classes (e.g. "category") for hidden inputs instead of duplicate IDs.
                                                foreach ($timePeriods as $period) {
                                                    $date_from = date('Y-m-d', strtotime($period['date_from']));
                                                    $date_to   = date('Y-m-d', strtotime($period['date_to']));
                                                ?>
                                                    <form action="<?= base_url('graph/show') ?>" class="editor-graph graph-hide time-period-form" method="POST">
                                                        <input type="hidden" name="commodity_head" class="category" value="" />
                                                        <input type="hidden" name="commodity" class="subcategory" value="" />
                                                        <input type="hidden" name="commodityTwo" class="subcategoryTwo" value="" />
                                                        <input type="hidden" name="time" value="<?= $period['value'] ?>" />
                                                        <input type="hidden" name="weekss" value="<?= ($period['value'] == '1_months' || $period['value'] == '3_months') ? 'Day' : 'Month' ?>" />
                                                        <input type="hidden" name="date_from" class="from" value="<?= $date_from ?>" />
                                                        <input type="hidden" name="date_to" class="to" value="<?= $date_to ?>" />
                                                        <button type="submit" class="btn date_hover"><?= $period['label'] ?></button>
                                                    </form>
                                                <?php } ?>
                                            </div>
                                            <form id="frequencyForm" class="editor-graph" method="POST">
                                                <div class="data_freq_margin"
                                                    style="display: flex;justify-content: flex-start;padding-left: 20px;line-height: 1.75;">
                                                     <label for="" style="padding-right: 10px;">Data Frequency:</label>
                                                     <?php
                                                        // Define available frequency options
                                                        $frequencies = [
                                                            'Day' => 'Daily',
                                                            'Week' => 'Weekly',
                                                            'Month' => 'Monthly',
                                                            'Quarter' => 'Quarterly',
                                                            'Year' => 'Yearly'
                                                        ];
                                                        // Get the selected frequency from session or default to 'Month'
                                                             $selectedFrequency = $this->session->userdata('weeksd') ? $this->session->userdata('weeksd') : 'Month';
                                                    ?>
                                                    <div class="cs_radio">
                                                        <?php foreach ($frequencies as $value => $label): ?>
                                                            <input type="radio" name="weekss" value="<?= $value ?>" id="weekss_<?= $value ?>" 
                                                                class="<?= strtolower($value) ?>" <?= $selectedFrequency == $value ? 'checked' : '' ?>>
                                                            <?= $label ?>
                                                        <?php endforeach; ?>
                                                    </div>
                                                </div>
                                            </form>
                                        </div>
                                        <div class="right_side_icons">
                                            <!-- <i class="fa fa-star" style="font-size:24px;color:yellow"></i> -->  
                                            <!--<?php if (in_array($subs_type[0]['subscription_type'], ['6', '7', '8'])) { ?>
                                            <a href="<?= base_url('graph/view-pdf') ?>" style="margin:0px !important;"
                                            class="btn costmaster-button btn-sm mr-2"><i class="fa fa-file-pdf"></i> CIR - FC Reports </a>
                                            <?php } ?> -->
                                            <?php if (in_array($subs_type[0]['subscription_type'], ONLINE_CUSTOM_PARTIAL_ACCESS)) {?>
                                                <?php if (isset($_POST['commodity_head'])) {       
                                                    if (isset($num_record) && !empty($num_record) && $num_record > 0) {
                                                        if ($this->session->userdata('weeksd') == "Week" || $this->session->userdata('weeksd') == "Month" || $this->session->userdata('weeksd') == "Year" || $this->session->userdata('weeksd') == "Quarter" || $this->session->userdata('weeksd') == "Day") { ?>
                                            <a id="lineToBarToggle" data-toggle="tooltip" title="Change-Chart"
                                                class="graph_corner-icon"><img src="<?php echo base_url() ?>/assets/frontend/images/bar-c.png"></a>
                                            <?php  if ($commodityTwo != '')  { ?>
                                            <a id="dualAxesToggle" data-toggle="tooltip" title="Line-Column-Chart"
                                                class="graph_corner-icon"> <img src="<?php echo base_url() ?>/assets/frontend/images/linebar-chart.png"></a>
                                            <?php } ?>
                                            <a href="javascript:void(0);" id="btnFullscreen" data-toggle="tooltip"
                                               title="Full Screen" class="graph_corner-icon" style="margin:0px !important;"><img src="<?php echo base_url() ?>/assets/frontend/images/maximize.png"></a>
                                            <!-- add  Print PDF button to download current page by rajdeep 30-03-2024 -->
                                            <a id="printPdfBtn" data-toggle="tooltip" title="PDF"
                                                style="cursor:pointer;  margin: 0px !important;" class="graph_corner-icon"> <img src="<?php echo base_url() ?>/assets/frontend/images/printer.png"></a>
                                            <a style="cursor:pointer; margin:0px !important;" id="excelDownloadButton"
                                                data-toggle="tooltip" title="Export" class="graph_corner-icon">
                                                <img src="<?php echo base_url() ?>/assets/frontend/images/export.png"></a>
                                            <a style="cursor:pointer; margin:0px !important;"href="javascript:void(0);" id="manual_book" data-toggle="tooltip" title="User Manual" class="graph_corner-icon"><img src="<?php echo base_url() ?>/assets/frontend/images/manual-book.png"></a>
                                                    <?php }
                                                    }
                                                } ?>
                                            <?php } ?>
                                        </div>
                                    </div>
                                </div>
                                <?php if (($commodity != '' || $commodityTwo != '') && (!empty($num_record) && $num_record > 0)) { ?>
                                    <div class="commodity_graph">
                                        <?php if (in_array($subs_type[0]['subscription_type'], ONLINE_CUSTOM_PARTIAL_ACCESS)) { 
                                            // Initialize variables for calculations
                                            $num_record = $difference = $percent = 0;
                                            $avg_diff = $avg_percent = $percent_min_max = $diff_min_max = $percent_min = $diff_min = 0;

                                            // Determine the appropriate price data based on frequency

                                            switch ($this->session->userdata('weeksd')) {
                                                case 'Week':
                                                    $num_record = count($week_price_one);
                                                    break;
                                                case 'Month':
                                                    $num_record = count($month_price_one);
                                                    break;
                                                case 'Year':
                                                    $num_record = count($year_price_one);
                                                    break;
                                                case 'Quarter':
                                                    $num_record = count($quarterly_price_one);
                                                    break;
                                                default:
                                                    $num_record = count($price_one);
                                                    break;
                                            }
                                        ?>
                                        <figure class="highcharts-figure">
                                            <div class="row">
                                                <?php
                                                $head = isset($_POST['commodity_head']) ? $_POST['commodity_head'] : $this->session->userdata('commodity_head');
                                                $comm = isset($_POST['commodity']) ? $_POST['commodity'] : $commodity;
                                                ?>
                                                <?php
                                                $head = isset($_POST['commodity_head']) ? $_POST['commodity_head'] : $this->session->userdata('commodity_head');
                                                $comm = isset($_POST['commodity']) ? $_POST['commodity'] : $commodity;
                                                ?>

                                            </div>
                                            <div class="row">
                                                <div class="col-md-12 d-flex justify-content-start align-items-start "
                                                    style="gap:15px;">
                                                    <div class="commodity-info">
                                                        <?php if ($commodity != '') { ?>
                                                        <p>Commodity :
                                                            <?php echo $commodity; ?>  (
                                                            <?php foreach ($price_exis as $pe) {
                                                                echo $pe['chart_exis_duty'];
                                                                    }
                                                                    ?>)
                                                        </p>
                                                        <?php } if ($commodityTwo != '') { ?>
                                                        <p>Comparison Commodity :
                                                            <?php echo $commodityTwo; ?> (<?php foreach ($price_exis2 as $pe2) { echo $pe2['chart_exis_duty']; } ?>)
                                                        </p>
                                                        <?php } ?>
                                                    </div>                                            
                                                    <div class="website_url d-flex justify-content-end align-items-end">
                                                         <?php if ($commodity != '') { ?>
                                                        <!-- <a href="<?= preg_replace('/^https?:\/\//', '', base_url()) ?>"><?php echo preg_replace('/^https?:\/\//', '', base_url()) ?></a> -->
                                                        <a style="color: blue;"><?php echo rtrim(preg_replace('/^https?:\/\//', '', base_url()), '/'); ?></a>

                                                    <?php } ?>
                                                    </div>
                                                </div>
                                            </div>
                                            <?php
                                                if (isset($_POST['commodity_head'])) {
                                                    if ($num_record > 0) {
                                                        echo "<div id='container2'></div>";
                                                    } else {
                                                        echo "<div>No records found!</div>";
                                                    }
                                                } else {
                                                    echo "<div id='label-container'></div>";
                                                }
                                                ?>
                                        </figure>
                                        <?php } ?>
                                    </div>
                                    <?php if (!in_array($subs_type[0]['subscription_type'], PDF_ACCESS)) { ?>
                                        <div class="note-sec">
                                            <h5>Notes</h5>
                                            <p>1) Choose between Daily, Weekly, Monthly, or Yearly data views. Each data point represents the average price for the chosen period. For example, a "Monthly" view on May 1st reflects the average price for the entire month of May.</p>
                                            <p>2) The "Max" and "Min" values under analysis section reflect the actual highest and lowest values recorded within the selected date range. However, the data plotted on the graph may be averaged based on your chosen frequency (weekly, monthly, or yearly).</p>
                                            <p>3) Excel data export will work only if the user selects data frequency as a Monthly.</p>
                                            <p>4) "H" represents the highest value shown on the vertical axis, and "L" represents the lowest.</p>
                                            <p>5) The sloped trendline on the graph indicates the overall price trend. Upward = price increase, Downward = price decrease, Flat = no significant change.</p>
                                            <p>6) Average line shows the average price of the commodity for the selected date range.</p>
                                            <p>7) Price comparisons MOM (Month-over-Month) show the average price of the last three months within the same year. YOY (Year-over-Year) shows the average price of the last three years.</p>
                                            <p>8) Click "Data Legends" to hide or unhide specific lines on the graph for clearer comparison.</p>
                                            <p>9) Disclaimer: This data provides a general price trend. Users should interpret and use it at their own discretion.</p>
                                        </div>
                                    <?php } ?>
                                <?php } else { ?>
                                    
                                     <?php
                                        // Check if form was submitted and no commodity is selected
                                        if ($_SERVER["REQUEST_METHOD"] == "POST" && 
                                            ($commodity == '' && $commodityTwo == '') && 
                                            ($SelectedStart == '' && $SelectedEnd == '')) { 
                                        ?>
                                            <div class="toast text-info">
                                                Please select the Required Fields.
                                            </div>
                                        <?php 
                                        }  
                                        // Check if form was submitted and no data exists for the selected period and commodity
                                        if ($_SERVER["REQUEST_METHOD"] == "POST" && ($commodity != '' || $commodityTwo != '') && empty($num_record)) { 
                                        ?>
                                            <div class="toast text-info">
                                                 <?php $_SERVER["REQUEST_METHOD"] == "POST" && ($commodity != '' || $commodityTwo != '') && empty($num_record);  ?>
                                                No data available for the selected period and commodity.
                                            </div>
                                        <?php 
                                        } 
                                }  ?>
                            </div>
                    
                    </div>
                </div> <!-- main row div -->

           
        </div>
    </div>
</div>
<!--end::Section-->
<!-- </div>
</div> -->
<?php } else { ?>
<div class="kt-container  kt-container--fluid  kt-grid__item kt-grid__item--fluid" style="margin-top:30px"><!--begin::Portlet-->
    <div class="kt-portlet">
        <div class="kt-portlet__body">
            <!--begin::Section-->
            <div class="kt-section">
                <div class="kt-section__content">
                    <form action="<?= base_url('graph'); ?>" method="POST" class="agree_terms">
                        <div class="form-row">
                            <div class="col-sm-12">
                                <div class="user-info-box pricing-list">
                                    <h5>Subscriber Agreement - Terms &amp; Conditions</h5>
                                    <ul class="subscription-ul">
                                        <li>Subscription will start within 5 working days of realization of payment in
                                            normal working conditions.</li>
                                        <li>Objective of this endeavor is to provide relevant information for strategic
                                            decision making & not meant for influencing commercial transactions. Our
                                            liability is restricted to providing of information and not the resultant.
                                        </li>
                                        <li>You will not share, publish, upload, transmit, reproduce, redistribute or in
                                            any other manner make available the statistical information compiled and
                                            provided by CostMasters, without the express prior permission of
                                            CostMasters. On being permitted, the user shall always mention the source of
                                            the statistical information i.e. CostMasters.</li>
                                        <li>Any incidence of single copy being used by multiple users will result in
                                            immediate cancellation of supply of statistical information without any
                                            refund for the remaining period.</li>
                                        <li>Depending on availability of data from respective sources, commodities may
                                            increase and decrease time to time at sole discretion of CostMasters.</li>
                                        <li>CostMasters reserve the sole right to review increase or decrease
                                            subscription charges.</li>
                                        <li>User indemnifies CostMasters from any damage resulting from
                                            mis-interpretation or use of data. CostMasters legal liability is strictly
                                            restricted to subscription amount paid by user.</li>
                                        <li>In case of any taxes or levies imposed by tax authorities during the period
                                            of subscription, user will have to bear and pay the balance amount, enabling
                                            us to ensure continuous services.</li>
                                        <li>Although all the efforts are being made to ensure diligence and accuracy of
                                            data, still some errors may occur, which will be corrected time to time.
                                        </li>
                                        <li>In case of Hardware or software malfunction, we will try our best to restore
                                            the services in minimum possible time. User will have to bear with us during
                                            such unavoidable circumstances</li>
                                        <li>Any dispute is subject to chandigarh jurisdiction.</li>
                                    </ul>
                                    <div class="form-group">
                                        <h5><input type="checkbox" name="agreement_tick" id="agreement_tick" required>
                                            Agree to Subscriber Agreement terms*</h5>
                                        <button type="submit" class="btn costmaster-button">Submit</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <!--end::Section-->
    </div>
</div>
<?php } ?>
<style>
#today,
#one,
#three,
#six,
#nine,
#ytd,
#fullyear,
#week,
#month,
#year {
    display: none !important;
}
/* Toast styling */
.toast {
    min-width: 250px;
    background-color: #f1f6fd;; /* Bootstrap 'info' color */
    color: #5c6072;
    text-align: center;
    padding: 12px;
    position: fixed;
    top: 70px;
    right: 20px;
    border-radius: 5px;
    font-size: 14px;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);

    /* Animation */
    opacity: 1;
    animation: fadeOut 8s ease-in-out forwards;
}

/* Fade out after 3 seconds */
@keyframes fadeOut {
    0% { opacity: 1; }
    100% { opacity: 0; }
}

/* .highcharts-figure{display: none;} */
</style>

<script src="<?= base_url(); ?>assets/plugins/general/jquery/dist/jquery.js" type="text/javascript"></script>
<script src="<?= base_url(); ?>assets/plugins/general/select2/dist/js/select2.full.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
  // Cache master dropdown elements
  const $commodityHead = $('#commodity_head');
  const $commodity = $('#commodity');
  const $commodityTwo = $('#commodityTwo');
  const $commHeadHide = $('.commHeadHide');
  const $form = $('form.graph-hide');
  const $timePeriodButtons = $('.time-period-form button');

  // -------------------------------
  // In-memory variables for last selections (defaults from PHP)
  // -------------------------------
  let lastCommodity = "<?php echo $commodity; ?>";
  let lastCommodityTwo = "<?php echo isset($commodityTwo) ? $commodityTwo : ''; ?>";
  let isOptionsLoading = false; // Flag to indicate AJAX loading in progress

  // -------------------------------
  // Helper Functions for Select2
  // -------------------------------
  const formatState = state => {
    if (!state.id) return state.text;
    return $('<span>' + state.text + '</span>');
  };

  const initSelect2 = ($element, templateFn) => {
    $element.select2({
      templateResult: templateFn,
      width: '100%'
    });
  };

  // -------------------------------
  // Initialize select2 on master dropdowns
  // -------------------------------
  initSelect2($commodityHead, formatState);
  initSelect2($commodity, formatState);
  initSelect2($commodityTwo, formatState);

  // -------------------------------
  // Show/Hide Comparison Section Based on PHP Default
  // -------------------------------
  const selectedCommodityTwo = '<?php echo $commodityTwo; ?>';
  if (selectedCommodityTwo !== '') {
    $commHeadHide.show();
  } else {
    $commHeadHide.hide();
  }

  // -------------------------------
  // Utility Functions (Without sessionStorage)
  // -------------------------------
  // Set the select box's value and trigger change
  const selectOptionByValue = ($select, value) => {
    $select.val(value).trigger('change');
  };

  // Update dropdowns using AJAX response and restore stored selections.
  // If a stored selection is missing, leave the dropdown at the default placeholder.
  const updateDropdowns = data => {
    const defaultOption1 = '<option value="">Commodity</option>';
    const defaultOption2 = '<option value="">Comparison Commodity</option>';
    $commodity.html(defaultOption1 + data);
    $commodityTwo.html(defaultOption2 + data);

    // Destroy existing select2 instances to avoid layout issues.
    if ($commodity.data('select2')) $commodity.select2('destroy');
    if ($commodityTwo.data('select2')) $commodityTwo.select2('destroy');

    // Reinitialize select2
    initSelect2($commodity, formatState);
    initSelect2($commodityTwo, formatState);

    // Restore stored selections if they exist; otherwise, clear them.
    if ($commodity.find(`option[value="${lastCommodity}"]`).length > 0) {
      selectOptionByValue($commodity, lastCommodity);
    } else {
      lastCommodity = "";
      $commodity.val("");
    }
    if ($commodityTwo.find(`option[value="${lastCommodityTwo}"]`).length > 0) {
      selectOptionByValue($commodityTwo, lastCommodityTwo);
    } else {
      lastCommodityTwo = "";
      $commodityTwo.val("");
    }
    
    toggleCommodityTwo();
    // Re-enable time-period buttons now that the options are updated.
    $timePeriodButtons.prop('disabled', false);
    isOptionsLoading = false;
  };

//cutom web access dependent dropdown
<?php 
if (!empty($subs_type) && isset($subs_type[0]['subscription_type'])): 

    // Check if the subscription type is custom
    if (in_array($subs_type[0]['subscription_type'], CUSTOM_ACCESS)) {
        // Get the allowed item IDs for this user
        $allowed_items = $subs_type[0]['item_ids'];
    } else {
        $allowed_items = []; // Empty array means show all items
    }
?>
// Pass allowed items to JavaScript
const allowedItems = <?= json_encode($allowed_items); ?>;
<?php endif; ?>
  // AJAX: Load commodity options based on commodity_head value.
  const loadCommodityOptions = commodity_head => {
    if (commodity_head) {
      isOptionsLoading = true;
      // Disable master dropdowns and time period buttons during AJAX loading.
      $commodity.prop('disabled', true);
      $commodityTwo.prop('disabled', true);
      $timePeriodButtons.prop('disabled', true);
      
      $.ajax({
        url: "<?= base_url('graph/commodity'); ?>",
        method: "POST",
        data: { commodity_head: commodity_head,
                allowed_items: allowedItems // Now correctly passed from PHP
        },
        success: function (data) {
          updateDropdowns(data);
          $commodity.prop('disabled', false);
          toggleCommodityTwo();
        },
        error: function (xhr, status, error) {
          console.error("Error loading commodities: " + error);
          $commodity.prop('disabled', false);
          $commodityTwo.prop('disabled', true);
          $timePeriodButtons.prop('disabled', false);
          isOptionsLoading = false;
        }
      });
    } else {
      $commodity.html('<option value="">--Commodity--</option>');
      $commodityTwo.html('<option value="">--Comparison Commodity--</option>');
    }
  };

  // Enable/disable commodityTwo dropdown based on main commodity selection.
  // Also disable duplicate selection.
  const toggleCommodityTwo = () => {
    const selectedVal = $commodity.val();
    $commodityTwo.prop('disabled', !selectedVal);
    $commodityTwo.find('option').prop('disabled', false);
    if (selectedVal) {
      $commodityTwo.find(`option[value="${selectedVal}"]`).prop('disabled', true);
    }
  };

  // -------------------------------
  // Event Handlers
  // -------------------------------

  // When commodity_head changes, load new commodity options via AJAX.
  $commodityHead.change(function () {
    const commodity_head = $(this).val();
    loadCommodityOptions(commodity_head);
  });

  // When main commodity changes, update the in-memory value and toggle commodityTwo.
  $commodity.change(function () {
    lastCommodity = $(this).val();
    toggleCommodityTwo();
  });

  // When comparison commodity changes, update its in-memory value and disable duplicate in main commodity.
  $commodityTwo.change(function () {
    lastCommodityTwo = $(this).val();
    $commodity.find('option').prop('disabled', false);
    if (lastCommodityTwo) {
      $commodity.find(`option[value="${lastCommodityTwo}"]`).prop('disabled', true);
    }
  });

  // "Compare" button: Show the comparison section.
  $("#compare2").click(() => {
    $commHeadHide.show();
  });

  // On form submission, update hidden fields in the current form with current master dropdown values.
  $('.time-period-form').submit(function () {
    // Prevent submission if options are still loading.
    if (isOptionsLoading) {
      alert("Please wait until the commodity options are loaded.");
      return false;
    }
    const category = $commodityHead.val();
    const subcategory = $commodity.val();
    const comparecategory = $commodityTwo.val();

    $(this).find('input.category').val(category);
    $(this).find('input.subcategory').val(subcategory);
    $(this).find('input.subcategoryTwo').val(comparecategory);

    console.log("Submitting form with:", {
      commodity_head: category,
      commodity: subcategory,
      commodityTwo: comparecategory
    });
    return true;
  });

  // Reset button: Clear selections and reset dropdowns.
  $("#resetButton").click(function () {
    lastCommodity = "";
    lastCommodityTwo = "";
    $commodityHead.val('').trigger('change');
    $commodity.html('<option value="">Commodity</option>');
    $commodityTwo.html('<option value="">Comparison Commodity</option>');
  });


  // Initialize tooltips (if using Bootstrap)
  $('[data-toggle="tooltip"]').tooltip();

  // Update hidden field when a radio button with name "weekss" changes.
  $('input[name="weekss"]').change(function () {
    $('#weekss_hidden').val($(this).val());
  });

  // If commodity_head already has a value from PHP, trigger its change to load options.
  if ($commodityHead.val()) {
    $commodityHead.trigger('change');
  }
});

// blank highchart handle
$(document).ready(function () {
  // Define initial chart options using PHP-generated values.
  var options = {
    chart: {
      renderTo: 'container',
      type: 'line'
    },
    title: {
      text: 'Chart Items',
      x: -20  // Center title horizontally
    },
    subtitle: {
      text: '',
      x: -20
    },
    xAxis: {
      // PHP variable $date should output something like: 'Jan,Feb,Mar,...'
      categories: [<?php echo empty($date) ? "''" : $date; ?>]
    },
    yAxis: {
      title: {
        text: 'Price'
      },
      plotLines: [{
        value: 0,
        width: 1,
        color: '#808080'
      }]
    },
    tooltip: {
      formatter: function () {
        return '<b>' + this.series.name + '</b><br>' +
               this.x + ': ' + this.y + '<br>' +
               'Note: Your note here';
      }
    },
    // PHP variable $cost should output valid series data (e.g. a JSON array)
    series: [<?php echo empty($cost) ? 0 : $cost; ?>]
  };

  // Optionally, you can update chart options with JSON data from the server.
  // This example fetches JSON from a given URL and then overwrites the categories
  // and the first series data before creating the chart.
  $.getJSON("<?php echo base_url('graph/show/graph-result'); ?>", function (json) {
    // Uncomment the following lines if you wish to update from the JSON response:
    // options.xAxis.categories = json[0].data;
    // options.series[0] = json[1];

    // Otherwise, use the PHP-generated data:
    options.xAxis.categories = <?php echo empty($date) ? "''" : $date; ?>;
    options.series[0] = <?php echo empty($cost) ? 0 : $cost; ?>;

    // Create the chart with the defined options.
    chart = new Highcharts.Chart(options);
  });
});
</script>
<?php
if ($commodity != '' && $commodityTwo != '') {
?>
<script>
// Set the document title dynamically
$(document).prop('title', 'CostMasters - <?php echo $commodity; ?> / <?php echo $commodityTwo; ?>');

// Get number of records from PHP
var no_of_record = "<?php echo $num_record; ?>";

// ---------------------------------------------------------------------
// Extend Highcharts with a custom downloadXLSX function using zipcelx
// ---------------------------------------------------------------------
(function(H) {
    if (window.zipcelx && H.getOptions().exporting) {
        H.Chart.prototype.downloadXLSX = function() {
            // Create a temporary hidden div (if needed)
            const tempDiv = document.createElement('div');
            tempDiv.style.display = 'none';
            document.body.appendChild(tempDiv);
            
            // Retrieve data rows from the chart
            const rows = this.getDataRows(true);
            // Process rows (skip header row)
            const xlsxRows = rows.slice(1).map((row, index) => 
                row.map(column => {
                    if (index === 0) {
                        return {
                            type: typeof column === 'number' ? 'number' : 'string',
                            value: column
                        };
                    } else {
                        const referenceDate = new Date(rows[rows.length - 1][0]);
                        const oneYearAgo = new Date(
                            referenceDate.getFullYear() - 1,
                            referenceDate.getMonth(),
                            referenceDate.getDate()
                        );
                        const currentDate = new Date(row[0]);
                        console.log(currentDate, referenceDate);
                        if (currentDate > oneYearAgo) {
                            return {
                                type: typeof column === 'number' ? 'number' : 'string',
                                value: column
                            };
                        } else {
                            return { type: 'string', value: '' };
                        }
                    }
                })
            );

            // Determine filename from exporting options or fallback to PHP variables
            let name;
            if (this.options.exporting.filename) {
                name = this.options.exporting.filename;
            } else if (this.title && this.title.textStr) {
                name = this.title.textStr.replace(/ /g, '-').toLowerCase();
            } else {
                name = '<?php echo $commodity; ?> / <?php echo $commodityTwo; ?>';
            }

            // Filter out rows with an empty first cell and generate XLSX
            window.zipcelx({
                filename: name,
                sheet: {
                    data: xlsxRows.filter(row => row[0].value !== '')
                }
            });
            
            // Clean up
            document.body.removeChild(tempDiv);
        };

        // Set language string for the XLSX download option
        H.getOptions().lang.downloadXLSX = 'Download XLSX';

        // Add the menu item definition for XLSX download
        H.getOptions().exporting.menuItemDefinitions.downloadXLSX = {
            textKey: 'downloadXLSX',
            onclick: function() {
                this.downloadXLSX();
            }
        };

        // Replace the default 'downloadXLS' item with our XLSX option
        const menuItems = H.getOptions().exporting.buttons.contextButton.menuItems;
        const index = menuItems.indexOf('downloadXLS');
        if (index !== -1) {
            menuItems[index] = 'downloadXLSX';
        }
    }
}(Highcharts));

// ---------------------------------------------------------------------
// Set global Highcharts options based on the record count
// ---------------------------------------------------------------------
if (parseInt(no_of_record) > 20) {
    Highcharts.setOptions({
        colors: ['#5867dd', '#F46D75'],
        plotOptions: {
            line: {
                marker: {
                    radius: 3,
                    lineColor: '',
                    lineWidth: 3
                },
                dataLabels: {
                    allowOverlap: false,
                    style: {
                        fontSize: '14px'
                    }
                }
            }
        }
    });
} else {
    Highcharts.setOptions({
        colors: ['#5867dd', '#F04A00'],
        plotOptions: {
            line: {
                marker: {
                    radius: 3,
                    lineColor: '',
                    lineWidth: 3
                },
                dataLabels: {
                    enabled: true,
                    allowOverlap: false,
                    style: {
                        fontSize: '14px'
                    }
                },
                enableMouseTracking: true
            }
        }
    });
}

// ---------------------------------------------------------------------
// Output date components as a JavaScript object using JSON
// ---------------------------------------------------------------------
<?php 
    $date1 = new DateTime($startDate);
    $year1 = $date1->format('Y');
    $month1 = $date1->format('n') - 1; // Convert to zero-based index for JS
    $day1 = $date1->format('d');

    $date2 = new DateTime($endDate);
    $year2 = $date2->format('Y');
    $month2 = $date2->format('n') - 1; // Convert to zero-based index
    $day2 = $date2->format('d');

    $gmdateArray = [
        'start' => ['year' => $year1, 'month' => $month1, 'day' => $day1],
        'end'   => ['year' => $year2, 'month' => $month2, 'day' => $day2]
    ];
?>
var gmdate = <?php echo json_encode($gmdateArray); ?>;
console.log('gmdate:', gmdate);


// ------------------------------------------------------
// Adds a centered watermark image to the chart
// ------------------------------------------------------
const addWatermark = (chart) => {
  const watermarkWidth = 650;
  const watermarkHeight = 300;
  let watermark;

  const updateWatermark = () => {
    // Use chartWidth/Height for the entire chart container
    const chartWidth = chart.chartWidth;
    const chartHeight = chart.chartHeight;
    if (!chart || !chart.renderer) {
      console.error('Chart object or renderer is not available.');
      return;
    }
    if (watermark) {
      watermark.destroy();
    }
    const watermarkX = (chartWidth - watermarkWidth) / 2;
    const watermarkY = (chartHeight - watermarkHeight) / 2; // Center vertically
    watermark = chart.renderer
      .image(
        '<?= base_url("assets/frontend/images/watermark.png") ?>',
        watermarkX,
        watermarkY,
        watermarkWidth,
        watermarkHeight
      )
      .attr({
        zIndex: -9999,
        style: 'pointer-events:none;opacity:0.7;transform: rotate(0deg);',
        class: 'watermark-image'
      })
      .add();
  };

  // Initially add watermark and update on redraw
  updateWatermark();
  chart.options.chart.events.redraw = updateWatermark;
};

// ------------------------------------------------------
// Adds a plot line with a styled label to a given yAxis
// ------------------------------------------------------
const addMultiPlotLine = (yAxis, value, label, color) => {
  yAxis.addPlotLine({
    value,
    color,
    width: 1,
    zIndex: 5,
    dashStyle: 'Dash',
    label: {
      // Uncomment or adjust text as needed:
      // text: `${label} Price: ${value.toFixed(2)}`,
      align: 'left',
      verticalAlign: 'top',
      y: -30,
      style: {
        color,
        fontSize: '12px',
        fontWeight: 'bold',
        backgroundColor: 'lightblue',
        padding: '5px',
        borderRadius: '5px',
        borderColor: 'blue',
        borderWidth: '1px'
      }
    }
  });
};

// ------------------------------------------------------
// Creates and returns a chart label at a specified position
// ------------------------------------------------------
const addLabel = (chart, text, color, x, y) => {
  return chart.renderer
    .text(text, x, y)
    .attr({
      zIndex: 5,
      fill: color,
      fontSize: '14px',
      fontWeight: 'bold'
    })
    .css({
      color,
      fontSize: '14px',
      fontWeight: 'bold'
    })
    .addClass('hover-label')
    .add();
};

// ------------------------------------------------------
// Calculates a simple linear trendline for an array of data
// ------------------------------------------------------
const calculateTrendline = (data) => {
  const validData = data
    .map((point, index) => ({ index, value: point }))
    .filter(({ value }) => value !== null && !isNaN(value));
  const n = validData.length;
  if (n === 0) return [];
  const sumX = validData.reduce((acc, { index }) => acc + index, 0);
  const sumY = validData.reduce((acc, { value }) => acc + value, 0);
  const sumXY = validData.reduce((acc, { index, value }) => acc + index * value, 0);
  const sumX2 = validData.reduce((acc, { index }) => acc + index ** 2, 0);
  const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX ** 2);
  const intercept = (sumY - slope * sumX) / n;

  return data.map((point, i) =>
    point !== null && !isNaN(point) ? slope * i + intercept : null
  );
};

// ------------------------------------------------------
// Adds a trendline series to the chart for a given series data
// ------------------------------------------------------
const addTrendline = (chart, series, data, showDataLabels = false) => {
  // Calculate trendline points
  const trendlinePoints = calculateTrendline(data);

  // Determine which y-axis to use: assign trendline to opposite axis of the input series
  const yAxisIndex = series.yAxis.opposite ? 0 : 1;
  // Set color based on yAxis: primary uses one color, secondary another
  const color = series.yAxis.opposite ? '#1560BD' : '#FF7518';

  // Add the trendline series to the chart
  chart.addSeries({
    name: `${series.yAxis.opposite ? 'Secondary' : 'Primary'} Trendline`,
    type: 'line',
    color,
    lineWidth: 0.5,
    marker: { enabled: false },
    data: trendlinePoints.map(point => (point !== null ? parseFloat(point.toFixed(1)) : null)),
    dataLabels: {
      enabled: showDataLabels,
      color: series.color,
      style: { fontSize: '14px' },
      formatter: function () {
        return this.y !== null ? this.y.toFixed(1) : '';
      }
    },
    zIndex: 2,
    yAxis: yAxisIndex
  });
};

// ------------------------------------------------------
// Calculates the average of valid data points in a series
// ------------------------------------------------------
const calculateAverage = (series) => {
  const validDataPoints = series.points
    .map(point => point.y)
    .filter(y => y !== null && !isNaN(y));
  if (validDataPoints.length === 0) return null;
  return validDataPoints.reduce((sum, value) => sum + value, 0) / validDataPoints.length;
};

// ------------------------------------------------------
// Calculates statistics (min, max, average), updates point labels,
// and adds trendlines and average lines for each series.
// ------------------------------------------------------
const calculateAndPlotStatistics = (chart) => {
  chart.series.forEach((series, index) => {
    const data = series.points.map(point => point.y);
    const validData = data.filter(val => val !== null && !isNaN(val));
    if (validData.length === 0) return;

    const maxPoint = Math.max(...validData);
    const minPoint = Math.min(...validData);
    const average = calculateAverage(series);
    const seriesType = series.yAxis.opposite ? 'Secondary' : 'Primary';

    let highestLabelAdded = false;
    let lowestLabelAdded = false;

    // If all data points are equal, update first and one later point with special labels
    if (data.every(val => val === data[0])) {
      series.points[0].update({
        dataLabels: {
          enabled: true,
          formatter: () => `H: ${maxPoint}`,
          style: { color: 'white', fontWeight: 'bold', fontSize: '14px' },
          backgroundColor: 'red',
          shape: 'rect',
          verticalAlign: series.index === 0 ? 'top' : 'bottom'
        }
      }, false);
      const lastPoint = series.points[series.points.length - 6] || series.points[series.points.length - 1];
      lastPoint.update({
        dataLabels: {
          enabled: true,
          formatter: () => `L: ${minPoint}`,
          style: { color: 'white', fontWeight: 'bold', fontSize: '14px' },
          backgroundColor: 'green',
          shape: 'rect',
          verticalAlign: series.index === 0 ? 'top' : 'bottom'
        }
      }, false);
    }

    // For each point, add data labels for the highest/lowest point (if not already added)
    series.points.forEach(point => {
      const isMax = point.y === maxPoint;
      const isMin = point.y === minPoint;
      if ((isMax && !highestLabelAdded) || (isMin && !lowestLabelAdded)) {
        // Adjust vertical position based on series index (example logic)
        const labelY = isMax
          ? (index % 2 === 0 ? -40 : 50)
          : (index % 2 === 0 ? 20 : -20);
        if (isMax) highestLabelAdded = true;
        if (isMin) lowestLabelAdded = true;
        point.update({
          dataLabels: {
            enabled: true,
            allowOverlap: true,
            formatter: function () {
              return `${isMax ? 'H' : 'L'}: ${this.y}`;
            },
            style: {
              color: 'white',
              fontWeight: 'bold',
              fontSize: '14px'
            },
            backgroundColor: isMax ? 'red' : 'green',
            borderWidth: 1,
            borderRadius: 3,
            shape: 'rect',
            verticalAlign: series.index === 0 ? 'top' : 'bottom',
            y: labelY
          }
        }, false);
      }
    });

    // Add trendline series for this series
    addTrendline(chart, series, data);

    // Add an average line series if average is valid
    if (average !== null) {
      const averageData = series.points.map(point =>
        point.y !== null && !isNaN(point.y) ? parseFloat(average.toFixed(1)) : null
      );
      chart.addSeries({
        name: `${seriesType} Average`,
        dashStyle: 'Dash',
        color: series.color,
        lineWidth: 1,
        marker: { enabled: false },
        data: averageData,
        zIndex: 3,
        dataLabels: { enabled: false },
        yAxis: series.yAxis.opposite ? 0 : 1
      });
    }
  });
};


// add the dyanmic code to allign the watermark in center according to width and height on multiple line chart by rajdeep kaur 29-03-2024 
var chart = Highcharts.chart('container2', {
  chart: {
    height: 435,
    events: {
      load: function () {
        addWatermark(this);            // Adds a watermark on chart load
        calculateAndPlotStatistics(this); // Plots statistics (e.g., average and trendlines)
      }
    }
  },
  title: {
    text: ''
  },
  subtitle: {
    text: '', // '<?= preg_replace('/^https?:\/\//', '', base_url()) ?>',
    align: 'right',
    floating: true,
    x: 0,
    style: {
      fontSize: '0.9em'
    }
  },
  xAxis: [{
    // Build categories from PHP data based on the selected interval
    categories: [
      <?php 
        if ($this->session->userdata('weeksd') == "Week") {
          foreach ($week_date as $week):
            echo "'" . $week['chart_date'] . "',";
          endforeach;
        } else if ($this->session->userdata('weeksd') == "Month") {
          foreach ($month_date as $month):
            echo "'" . date('M-Y', strtotime($month['chart_date'])) . "',";
          endforeach;
        } else if ($this->session->userdata('weeksd') == "Year") {
          foreach ($year_date as $year):
            echo "'" . date('Y', strtotime($year['chart_date'])) . "',";
          endforeach;
        } else if ($this->session->userdata('weeksd') == "Quarter") {
          foreach ($quarterly_date as $quarter):
            $quarterstartdate = new DateTime($quarter['chart_date']);
            $month = (int)$quarterstartdate->format('m');
            $startMonth = ($month - 1) - ($month - 1) % 3;
            $endMonth = $startMonth + 2;
            $startMonthName = $quarterstartdate->setDate($quarterstartdate->format('Y'), $startMonth + 1, 1)->format('M');
            $endMonthName = $quarterstartdate->setDate($quarterstartdate->format('Y'), $endMonth + 1, 1)->format('M');
            $year = $quarterstartdate->format('Y');
            echo "'" . $startMonthName . "-" . $endMonthName . " " . $year . "',";
          endforeach;
        } else {
          foreach ($chart_date as $chart):
            echo "'" . $chart['chart_date'] . "',";
          endforeach;
        }
      ?>
    ],
    labels: {
      style: {
        color: '#000',
        fontSize: '10px',
        fontWeight: '500'
      }
    },
    accessibility: {
      description: 'Chart Date'
    },
    crosshair: true,
    lineWidth: 0  // Hide the x-axis line
  }],
  yAxis: [
    { // Primary yAxis (right side)
      labels: {
        formatter: function () {
          return this.value;
        },
        style: {
          color: Highcharts.getOptions().colors[0],
          fontSize: '14px',
          fontWeight: '600'
        }
      },
      title: {
        text: '<?php 
          foreach ($right_uom as $right):
            echo "<strong>" . $right['chart_price_unit'] . "</strong>";
          endforeach; ?>',
        style: {
          color: Highcharts.getOptions().colors[0],
          fontSize: '0.8em',
          fontWeight: '600'
        }
      },
      opposite: true
    },
    { // Secondary yAxis (left side)
      gridLineWidth: 0,
      title: {
        text: '<?php 
          foreach ($left_uom as $left):
            echo "<strong>" . $left['chart_price_unit'] . "</strong>";
          endforeach; ?>',
        style: {
          color: Highcharts.getOptions().colors[1],
          fontSize: '0.8em',
          fontWeight: '600'
        }
      },
      labels: {
        formatter: function () {
          return this.value;
        },
        style: {
          color: Highcharts.getOptions().colors[1],
          fontSize: '14px',
          fontWeight: '600'
        }
      }
    }
  ],
  tooltip: {
    backgroundColor: 'rgba(255, 255, 255, 0.9)', // White background with 80% opacity
    shared: true,
    // Note: This template syntax uses pseudo-code. If it doesn't work as expected,
    // consider using a custom formatter function.
    format: '<span style="font-size: 0.8em">{key}</span><br/>' +
            '{#each points}' +
            '<span style="color:{color}">\u25CF</span> ' +
            '{series.name}: <b>{y}</b><br/>' +
            '{/each}'
  },
  credits: {
    enabled: false
  },
  // Exporting configuration based on the selected interval (Month, Year, etc.)
  <?php if ($this->session->userdata('weeksd') == "Month") { ?>
  exporting: {
    enabled: false,
    csv: {
      dateFormat: '%Y-%m-%d'
    },
    buttons: {
      contextButton: {
        menuItems: ["viewFullscreen", "downloadXLS", "downloadXLSX"]
      }
    }
  },
  <?php } else if ($this->session->userdata('weeksd') == "Year") { ?>
  exporting: {
    enabled: false,
    csv: {
      dateFormat: '%Y-%m-%d'
    },
    buttons: {
      contextButton: {
        menuItems: ["viewFullscreen", "downloadXLSX"]
      }
    }
  },
  <?php } else { ?>
  exporting: {
    enabled: false,
    buttons: {
      contextButton: {
        menuItems: ["viewFullscreen"]
      }
    }
  },
  legend: {
    enabled: true,
    itemStyle: {
      fontSize: '12px',
      fontWeight: '600'
    }
  },
  <?php } ?>
  series: [
    {
      name: '<?php echo $commodity; ?>',
      color: Highcharts.getOptions().colors[1],
      marker: { symbol: 'diamond' },
      type: 'line',
      yAxis: 1,
      data: [
        <?php
          if ($this->session->userdata('weeksd') == "Week") {
            foreach ($Week_price_one as $one):
              echo isset($one) ? $one : 'null';
              echo ",";
            endforeach;
          } else if ($this->session->userdata('weeksd') == "Month") {
            foreach ($Month_price_one as $one):
              echo isset($one) ? $one : 'null';
              echo ",";
            endforeach;
          } else if ($this->session->userdata('weeksd') == "Year") {
            foreach ($Year_price_one as $one):
              echo isset($one) ? $one : 'null';
              echo ",";
            endforeach;
          } else if ($this->session->userdata('weeksd') == "Quarter") {
            foreach ($Quarterly_price_one as $one):
              echo isset($one) ? $one : 'null';
              echo ",";
            endforeach;
          } else {
            foreach ($Price_one as $one):
              echo isset($one) ? floatval(str_replace(",", "", $one)) : 'null';
              echo ",";
            endforeach;
          }
        ?>
      ]
    },
    {
      name: '<?php echo $commodityTwo; ?>',
      color: Highcharts.getOptions().colors[0],
      marker: { symbol: 'diamond' },
      type: 'line',
      data: [
        <?php
          if ($this->session->userdata('weeksd') == "Week") {
            foreach ($Week_price_two as $two):
              echo isset($two) ? $two : 'null';
              echo ",";
            endforeach;
          } else if ($this->session->userdata('weeksd') == "Month") {
            foreach ($Month_price_two as $two):
              echo isset($two) ? $two : 'null';
              echo ",";
            endforeach;
          } else if ($this->session->userdata('weeksd') == "Year") {
            foreach ($Year_price_two as $two):
              echo isset($two) ? $two : 'null';
              echo ",";
            endforeach;
          } else if ($this->session->userdata('weeksd') == "Quarter") {
            foreach ($Quarterly_price_two as $two):
              echo isset($two) ? $two : 'null';
              echo ",";
            endforeach;
          } else {
            foreach ($Price_two as $two):
              echo isset($two) ? floatval(str_replace(",", "", $two)) : 'null';
              echo ",";
            endforeach;
          }
        ?>
      ]
    }
  ]
});


// Global variables
var chart;
var chartType = 'line'; // Initialize with line type by default
var initialPrimaryYAxisMin = null; // Store the initial minimum value for the primary y-axis
var initialSecondaryYAxisMin = null; // Store the initial minimum value for the secondary y-axis
var isLineSeries = true;
var clickCount = 0;

// Function to toggle between line and column chart types for the first two series
function toggleChartType() {
    // Get the current type of the first series
    var currentType = chart.series[0].type;
    console.log(currentType);
    // If the current type is line, change it to bar, else change it to line
    var newType = currentType === 'line' ? 'column' : 'line';
   

    var commodityName = <?php echo json_encode($commodity); ?>;
    var commodityNameTwo = <?php echo json_encode($commodityTwo); ?>;
    // console.log(commodityName);
    // Iterate over all series and update their types
    chart.series.forEach(function(series) {
        //  console.log(series.name);
        if (series.name.includes(commodityName) || series.name.includes(commodityNameTwo)) {
           // console.log(newType);

            series.update({
                type: newType,
                dataLabels: {
                    enabled: series.options.dataLabels.enabled,
                     style: {
                        fontSize: '14px' // Adjust the font size as needed
                    }
                }
            }, true);
        }
    });

   // Update the y-axis minimum values if it's a column chart type
    if (newType === 'column') {
        if (initialPrimaryYAxisMin === null) {
            initialPrimaryYAxisMin = getDefaultYAxisStartValue(chart.series[1]);
        }
        if (initialSecondaryYAxisMin === null) {
            initialSecondaryYAxisMin = getDefaultYAxisStartValue(chart.series[0]);
        }
        const roundedPrimaryMin = Math.round(initialPrimaryYAxisMin);
        const roundedSecondaryMin = Math.round(initialSecondaryYAxisMin);
        console.log(chart.yAxis[0]);
        chart.yAxis[0].update({
            min: roundedPrimaryMin
        });
        chart.yAxis[1].update({
            min: roundedSecondaryMin
        });
    }

    // Update the last selected type
    chartType = newType;

    // Redraw the chart to apply the changes
    chart.redraw();
}

function getDefaultYAxisStartValue(series) {
    // Retrieve all data points of the series
    var allData = [];
    series.data.forEach(function(point) {
        allData.push(point.y);
    });
    // Calculate the minimum value of all data points
    var minData = Math.min.apply(null, allData);
    // Round down to the nearest integer for the secondary y-axis
    var yAxisStartValue = Math.floor(minData);
    // For the primary y-axis, subtract a buffer
    if (series.yAxis.options.index === 0) {
        yAxisStartValue = Math.round(minData - 2);
    }

    return yAxisStartValue;
}

function toggleLineAndBarSeries() {
    // Toggle between line and bar series for the first two series
    for (var i = 0; i < 2; i++) {
        var series = chart.series[i];

        if (isLineSeries) {
            // Convert line series to bar series
            if (series.type === 'line') {
                chart.series[0].update({
                    type: 'column',
                     dataLabels: {
                    enabled: series.options.dataLabels.enabled,
                     style: {
                        fontSize: '14px' // Adjust the font size as needed
                    }
                }
                });
            }
        } 
            // Convert bar series to line series
        if (series.type === 'column') {
                chart.series[1].update({
                    type: 'line',
                     dataLabels: {
                    enabled: series.options.dataLabels.enabled,
                     style: {
                        fontSize: '14px' // Adjust the font size as needed
                    }
                }
                });
        }
          // Adjust the minimum values for bar series
    if (initialPrimaryYAxisMin === null) {
        initialPrimaryYAxisMin = getDefaultYAxisStartValue(chart.series[1]);
    }
    if (initialSecondaryYAxisMin === null) {
        initialSecondaryYAxisMin = getDefaultYAxisStartValue(chart.series[0]);
    }
    chart.yAxis[0].update({
        min: Math.round(initialPrimaryYAxisMin) // Adjust the min value as needed
    });
    chart.yAxis[1].update({
        min: Math.round(initialSecondaryYAxisMin) // Adjust the min value as needed
    });
    }
   //console.log(series.type);
}

function displayDefaultLineChart() {
    for (var i = 0; i < 2; i++) {
        var series = chart.series[i];
            // Convert line series to bar series
             series.update({
                    type: 'line'
                });
        }
}

document.getElementById('lineToBarToggle').addEventListener('click', function() {
    toggleChartType('column'); // Toggle to column (bar) chart type
});

document.getElementById('dualAxesToggle').addEventListener('click', function() {
    clickCount++;
    if (clickCount === 2) {
        displayDefaultLineChart(); // Display only the default line chart on double click
        clickCount = 0; // Reset the click count
    } else {
        toggleLineAndBarSeries(); // Toggle between single and dual axes chart types
    }
});

// Toggle full-screen mode when button with ID 'btnFullscreen' is clicked
const fullScreenButton = document.getElementById('btnFullscreen');
if (fullScreenButton) {
  fullScreenButton.addEventListener('click', () => {
    if (chart && chart.fullscreen) {
      chart.fullscreen.toggle();
    } else {
      console.error('Chart or fullscreen module is not available.');
    }
  });
} else {
  console.error('Element with ID "btnFullscreen" not found.');
}


// ----- Date Formatting Functions -----
// ----- Date Formatting Functions -----
const formatMonth = (date) => {
  const options = { year: 'numeric', month: 'short' };
  return new Intl.DateTimeFormat('en-US', options).format(date);
};

const formatYear = (date) => date.getFullYear().toString();

const formatQuarter = (date) => {
  const month = date.getMonth();
  const startMonth = Math.floor(month / 3) * 3;
  const endMonth = startMonth + 2;
  const startMonthName = new Date(date.getFullYear(), startMonth)
    .toLocaleString('default', { month: 'short' });
  const endMonthName = new Date(date.getFullYear(), endMonth)
    .toLocaleString('default', { month: 'short' });
  return `${startMonthName}-${endMonthName} ${date.getFullYear()}`;
};

// ----- Determine if Excel download is enabled based on session -----
const isExcelDownloadEnabled = <?php echo ($this->session->userdata('weeksd') === "Month" 
    || $this->session->userdata('weeksd') === "Year" 
    || $this->session->userdata('weeksd') === "Quarter") ? 'true' : 'false'; ?>;

// Get the Excel download button and date input elements
const excelDownloadButton = document.getElementById('excelDownloadButton');
const toDateInput = document.getElementById('date_to');
const fromDateInput = document.getElementById('date_from');

// Only proceed if date inputs are present and have values
if (toDateInput && fromDateInput && toDateInput.value && fromDateInput.value) {
  const toDate = new Date(toDateInput.value);
  const fromDate = new Date(fromDateInput.value);

  if (isExcelDownloadEnabled && excelDownloadButton) {
    excelDownloadButton.addEventListener('click', () => {
      // Build CSV header
      let csvContent = "data:text/csv;charset=utf-8,";
      csvContent += "Date,";

      // Append commodity names (up to 2) for series that are not trendline/average
      let seriesCount = 0;
      chart.series.forEach((series) => {
        if (seriesCount < 2 && !series.options.isTrendline && !series.options.isAverage) {
          csvContent += series.name;
          seriesCount++;
          if (seriesCount < 2) csvContent += ",";
        }
      });
      csvContent += "\n";

      // Process chart categories and filter by date range
      const categories = chart.xAxis[0].categories;
      let filteredData = [];

      categories.forEach((category, i) => {
        // Convert the category to a Date object
        const date = new Date(category);
        let includeData = false;
        let formattedDate = "";

        // For "Year" mode: compare only the year parts
        if (<?php echo ($this->session->userdata('weeksd') === "Year") ? 'true' : 'false'; ?>) {
          const categoryYear = date.getFullYear();
          const fromYear = fromDate.getFullYear();
          const toYear = toDate.getFullYear();
          if (categoryYear >= fromYear && categoryYear <= toYear) {
            formattedDate = formatYear(date);
            includeData = true;
          }
        } else {
          // For "Month" or "Quarter" mode, use full date comparison (inclusive)
          if (date >= fromDate && date <= toDate) {
            if (<?php echo ($this->session->userdata('weeksd') === "Quarter") ? 'true' : 'false'; ?>) {
              formattedDate = formatQuarter(date);
            } else if (<?php echo ($this->session->userdata('weeksd') === "Month") ? 'true' : 'false'; ?>) {
              formattedDate = formatMonth(date);
            }
            includeData = true;
          }
        }

        if (includeData) {
          // Build a row with the formatted date and the corresponding series values (max 2)
          const row = { date: formattedDate, data: [] };
          chart.series.forEach((series) => {
            if (!series.options.isTrendline && !series.options.isAverage && row.data.length < 2) {
              row.data.push(series.data[i]?.y || '');
            }
          });
          filteredData.push(row);
        }
      });

      // Limit the exported data to the last 12 entries
      filteredData = filteredData.slice(-12);

      // Append each row to the CSV content
      filteredData.forEach((row) => {
        csvContent += `${row.date},${row.data.join(",")}\n`;
      });

      // Create a temporary link element and trigger the CSV download
      const encodedUri = encodeURI(csvContent);
      const link = document.createElement("a");
      link.setAttribute("href", encodedUri);
      link.setAttribute("download", "chart_data.csv");
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });
  } else if (excelDownloadButton) {
    excelDownloadButton.addEventListener('click', () => {
      Swal.fire({
        icon: 'error',
        title: '',
        text: "Excel data is only available for monthly, yearly, or quarterly selection.",
        showCloseButton: true
      });
    });
  }
} else {
  console.error('FROM or TO date input not found or empty.');
}
</script>
<?php
} else { ?>
<!-- single commidity data -->
<script>
// Set the document title dynamically
const no_of_record = "<?php echo $num_record; ?>";
$(document).prop('title', `CostMasters - <?php echo $commodity; ?>`);

// Update Highcharts options based on the number of records
if (parseInt(no_of_record) > 20) {
  Highcharts.setOptions({
    colors: ['#5867dd'],
    plotOptions: {
      line: {
        marker: {
          radius: 3,
          lineColor: '',
          lineWidth: 3
        },
        dataLabels: {
          style: {
            fontSize: '14px' // Adjust font size as needed
          }
        }
      }
    }
  });
} else {
  Highcharts.setOptions({
    colors: ['#5867dd'],
    plotOptions: {
      line: {
        marker: {
          radius: 3,
          lineColor: '',
          lineWidth: 3
        },
        dataLabels: {
          enabled: true,
          style: {
            fontSize: '14px'
          }
        },
        enableMouseTracking: true
      }
    }
  });
}

/* ====================================================
   XLSX Export Functionality via zipcelx
   ==================================================== */
(function (H) {
  // Check if zipcelx and exporting options exist
  if (window.zipcelx && H.getOptions().exporting) {
    // Extend the Chart prototype with a downloadXLSX function
    H.Chart.prototype.downloadXLSX = function () {
      const div = document.createElement('div');
      div.style.display = 'none';
      document.body.appendChild(div);

      // Get data rows from the chart (assumes getDataRows is available)
      const rows = this.getDataRows(true);
      console.log(rows);

      // Process rows to create XLSX data
      const xlsxRows = rows.slice(1).map((row, rowIndex) =>
        row.map((column) => {
          // For the header row (rowIndex 0) always output the value type
          if (rowIndex === 0) {
            return {
              type: typeof column === 'number' ? 'number' : 'string',
              value: column
            };
          } else {
            // Use the last row's first column as a reference date
            const referenceDate = new Date(rows[rows.length - 1][0]);
            const oneYearAgo = new Date(
              referenceDate.getFullYear() - 1,
              referenceDate.getMonth(),
              referenceDate.getDate()
            );
            const currentDate = new Date(row[0]);
            console.log(currentDate, referenceDate);

            // Only output data if the date is within the past year; otherwise return empty
            if (currentDate > oneYearAgo) {
              return {
                type: typeof column === 'number' ? 'number' : 'string',
                value: column
              };
            } else {
              return {
                type: 'string',
                value: ''
              };
            }
          }
        })
      );

      // Determine the filename for export
      let name;
      if (this.options.exporting.filename) {
        name = this.options.exporting.filename;
      } else if (this.title && this.title.textStr) {
        name = this.title.textStr.replace(/ /g, '-').toLowerCase();
      } else {
        name = '<?php echo $commodity; ?>';
      }

      // Remove any rows that have an empty first cell
      const filteredRows = xlsxRows.filter((row) => row[0].value !== '');

      // Use zipcelx to generate the XLSX file
      window.zipcelx({
        filename: name,
        sheet: {
          data: filteredRows
        }
      });

      // Clean up the temporary div
      document.body.removeChild(div);
    };

    // Set default language string for download XLSX (overridable via i18n options)
    H.getOptions().lang.downloadXLSX = 'Download XLSX';

    // Add a menu item for XLSX download
    H.getOptions().exporting.menuItemDefinitions.downloadXLSX = {
      textKey: 'downloadXLSX',
      onclick: function () {
        this.downloadXLSX();
      }
    };

    // Replace the existing 'downloadXLS' menu item with 'downloadXLSX'
    const menuItems = H.getOptions().exporting.buttons.contextButton.menuItems;
    const index = menuItems.indexOf('downloadXLS');
    if (index !== -1) {
      menuItems[index] = 'downloadXLSX';
    }
  }
}(Highcharts));


// ------------------------------------------------------
// Function to add a plot line to a given yAxis
// ------------------------------------------------------
function addPlotLine(yAxis, value, label, color) {
  yAxis.addPlotLine({
    value: value,
    color: color,
    width: 1,
    zIndex: 5,
    dashStyle: 'Dash',
    label: {
      // Uncomment or modify the text property as needed:
      // text: `${label} Price: ${value.toFixed(2)}`,
      align: 'left',
      verticalAlign: 'top',
      style: {
        color: color,
        fontSize: '12px',
        fontWeight: 'bold',
        backgroundColor: 'lightblue',
        padding: '5px',
        borderRadius: '5px',
        borderColor: 'blue',
        borderWidth: '1px'
      }
    }
  });
}

// ------------------------------------------------------
// Function to calculate a trendline from data points
// Uses simple linear regression
// ------------------------------------------------------
function calculateTrendline(data) {
  // Build an array of valid data points with their indices
  const validData = data
    .map((point, index) => ({ index, value: point }))
    .filter(point => point.value !== null && !isNaN(point.value));

  const n = validData.length;
  if (n === 0) return []; // Return empty if no valid data points

  // Compute sums needed for linear regression
  const sumX = validData.reduce((acc, p) => acc + p.index, 0);
  const sumY = validData.reduce((acc, p) => acc + p.value, 0);
  const sumXY = validData.reduce((acc, p) => acc + (p.index * p.value), 0);
  const sumX2 = validData.reduce((acc, p) => acc + (p.index ** 2), 0);

  // Calculate slope and intercept
  const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX ** 2);
  const intercept = (sumY - slope * sumX) / n;

  // Map each index to its corresponding trendline value (or null if invalid)
  return data.map((point, i) =>
    (point !== null && !isNaN(point)) ? slope * i + intercept : null
  );
}

// ------------------------------------------------------
// Function to add a label to the chart at a given position
// ------------------------------------------------------
function addLabel(chart, text, color, x, y) {
  return chart.renderer
    .text(text, x, y)
    .attr({
      zIndex: 5,
      style: {
        color: color,
        fontSize: '12px',
        fontWeight: 'bold'
      }
    })
    .css({
      color: color,
      fontSize: '14px',
      fontWeight: 'bold'
    })
    .addClass('hover-label')
    .add();
}

// ------------------------------------------------------
// Function to calculate statistics (average, trendline, etc.)
// and plot lines/labels on the chart.
// ------------------------------------------------------
function calculateAndPlotStatistics(chart) {
  const series = chart.series[0];
  const data = series.points.map(point => point.y);
  const maxPoint = Math.max(...data);
  const minPoint = Math.min(...data);
  const average = data.reduce((sum, v) => sum + v, 0) / data.length;

  // Add an "Average" series as a dashed line
  const averageSeries = chart.addSeries({
    name: 'Average',
    dashStyle: 'Dash',
    color: series.color,
    lineWidth: 1,
    marker: { enabled: false },
    data: Array(data.length).fill(parseFloat(average.toFixed(1))),
    dataLabels: { enabled: false },
    zIndex: 3
  });

  // Calculate and add the trendline series
  const trendlinePoints = calculateTrendline(data);
  chart.addSeries({
    name: 'Trendline',
    type: 'line',
    color: 'grey',
    lineWidth: 0.5,
    marker: { enabled: false },
    data: trendlinePoints.map(point => (point !== null ? parseFloat(point.toFixed(1)) : null)),
    dataLabels: {
      enabled: false,
      // If you wish to show labels on the trendline, enable and style as needed
      color: 'red',
      formatter: function() {
        return this.y !== null ? this.y.toFixed(1) : '';
      }
    },
    zIndex: 2
  });

  // Identify the indices for the highest and lowest data points
  const maxIndex = data.indexOf(maxPoint);
  const minIndex = data.indexOf(minPoint);
  const dataLabelsEnabled = series.points.length < 20; // Enable labels if fewer than 20 points

  // Update each point's data label
  series.points.forEach((point, index) => {
    const isMax = index === maxIndex;
    const isMin = index === minIndex;
    point.update({
      dataLabels: {
        enabled: dataLabelsEnabled || isMax || isMin,
        useHTML: true,
        color: isMax || isMin ? 'white' : 'black',
        formatter: function() {
          const value = this.y.toFixed(1);
          if (dataLabelsEnabled) {
            if (isMax) {
              return `<div style="border-radius: 3px; background-color: red;">H: ${value}</div>`;
            } else if (isMin) {
              return `<div style="border-radius: 3px; background-color: green;">L: ${value}</div>`;
            } else {
              return value;
            }
          } else {
            return isMax ? `H: ${value}` : isMin ? `L: ${value}` : value;
          }
        },
        style: {
          fontWeight: 'bold',
          fontSize: '14px'
        },
        backgroundColor: isMax ? 'red' : isMin ? 'green' : 'transparent',
        borderWidth: 1,
        borderRadius: 3,
        shape: 'rect'
      }
    });
  });

  // Show average price label on mouseover for the average series line
  averageSeries.graph.on('mouseover', function () {
    const averageLabelX = chart.plotLeft + chart.plotWidth * 0.00;
    const averageLabelY = chart.plotTop + chart.plotHeight * 0.5;
    const label = addLabel(chart, `${series.name} Average Price: ${average.toFixed(1)}`, 'green', averageLabelX, averageLabelY);
    label.css({ visibility: 'visible' });
  });

  // Remove the average label on mouseout
  averageSeries.graph.on('mouseout', function () {
    chart.container.querySelectorAll('.hover-label').forEach(label => label.remove());
  });
}


// update the dyanmic code to allign the watermark in center according to width and height on single line chart by rajdeep kaur 29-03-2024 
var chart = Highcharts.chart('container2', {
  chart: {
    height: 469,
    events: {
      load: function () {
        addWatermark(this); // Adds a watermark (assumes addWatermark is defined)
        calculateAndPlotStatistics(this); // Plots additional lines/statistics (assumes function exists)
      }
    }
  },
  title: {
    text: ''
  },
  subtitle: {
    text: '', // '<?= preg_replace('/^https?:\/\//', '', base_url()) ?>',
    align: 'right',
    x: 0,
    style: {
      fontSize: '1em'
    }
  },
  xAxis: [{
    categories: [
      <?php 
        if ($this->session->userdata('weeksd') == "Week") {
            foreach ($week_date as $week):
                echo "'" . $week['chart_date'] . "',";
            endforeach;
        } else if ($this->session->userdata('weeksd') == "Month") {
            foreach ($month_date as $month):
                echo "'" . date('M-Y', strtotime($month['chart_date'])) . "',";
            endforeach;
        } else if ($this->session->userdata('weeksd') == "Year") {
            foreach ($year_date as $year):
                echo "'" . date('Y', strtotime($year['chart_date'])) . "',";
            endforeach;
        } else if ($this->session->userdata('weeksd') == "Quarter") {
            foreach ($quarterly_date as $quarter):
                $quarterstartdate = new DateTime($quarter['chart_date']);
                $month = (int)$quarterstartdate->format('m');
                $startMonth = ($month - 1) - ($month - 1) % 3;
                $endMonth = $startMonth + 2; 
                $startMonthName = $quarterstartdate->setDate($quarterstartdate->format('Y'), $startMonth + 1, 1)->format('M');
                $endMonthName = $quarterstartdate->setDate($quarterstartdate->format('Y'), $endMonth + 1, 1)->format('M');
                $year = $quarterstartdate->format('Y');
                echo "'" . $startMonthName . "-" . $endMonthName . " " . $year . "',";
            endforeach;
        } else {
            foreach ($chart_date as $chart):
                echo "'" . $chart['chart_date'] . "',";
            endforeach;
        }
      ?>
    ],
    labels: {
      style: {
        color: '#000',
        fontSize: '10px',
        fontWeight: '500'
      }
    },
    accessibility: {
      description: 'Chart Date'
    },
    crosshair: true
  }],
  yAxis: {
    // Final yAxis settings using the left unit values.
    title: {
      text: '<?php 
                foreach ($left_uom as $left):
                  echo "<strong>" . $left['chart_price_unit'] . "</strong>";
                endforeach;
             ?>',
      style: {
        color: Highcharts.getOptions().colors[0],
        fontSize: '12px',
        fontWeight: '600'
      }
    },
    labels: {
      formatter: function () {
        return this.value;
      },
      style: {
        color: Highcharts.getOptions().colors[0],
        fontSize: '12px',
        fontWeight: '600'
      }
    },
    opposite: false,
    gridLineWidth: 1,
    plotLines: [{
      color: '#000',
      value: 0,
      width: 2,
      zIndex: 4
    }]
  },
  tooltip: {
    backgroundColor: 'rgba(255, 255, 255, 0.9)', // White background with 80% opacity
    shared: true,
    // If you need templating, consider using a formatter function.
    // The provided format uses a pseudo-template syntax that may not work by default.
    // For now, we'll leave it as is:
    format: '<span style="font-size: 0.8em">{key}</span><br/>' +
            '{#each points}' +
            '<span style="color:{color}">\u25CF</span> ' +
            '{series.name}: <b>{y}</b><br/>' +
            '{/each}'
  },
  credits: {
    enabled: false
  },
  // Conditional exporting options based on session data
  <?php if ($this->session->userdata('weeksd') == "Month") { ?>
  exporting: {
    enabled: false,
    buttons: {
      contextButton: {
        menuItems: ["viewFullscreen", "downloadXLSX"]
      }
    }
  },
  <?php } else if ($this->session->userdata('weeksd') == "Year") { ?>
  exporting: {
    enabled: false,
    buttons: {
      contextButton: {
        menuItems: ["viewFullscreen", "downloadXLSX"]
      }
    }
  },
  <?php } else { ?>
  exporting: {
    enabled: false,
    buttons: {
      contextButton: {
        menuItems: [] // No items by default
      }
    }
  },
  <?php } ?>
  series: [{
    name: '<?php echo $commodity; ?>',
    color: Highcharts.getOptions().colors[0],
    marker: {
      symbol: 'diamond'
    },
    type: 'line',
    yAxis: 0,
    data: [
      <?php 
        if ($this->session->userdata('weeksd') == "Week") {
            foreach ($week_price_one as $one):
                echo $one['chart_item_cost2'] . ",";
            endforeach;
        } else if ($this->session->userdata('weeksd') == "Month") {
            foreach ($month_price_one as $one):
                echo $one['chart_item_cost2'] . ",";
            endforeach;
        } else if ($this->session->userdata('weeksd') == "Year") {
            foreach ($year_price_one as $one):
                echo $one['chart_item_cost2'] . ",";
            endforeach;
        } else if ($this->session->userdata('weeksd') == "Quarter") {
            foreach ($quarterly_price_one as $one):
                if (is_array($one)) {
                    echo isset($one['chart_item_cost2']) ? $one['chart_item_cost2'] : 'null';
                } else {
                    echo $one !== null ? $one : 'null';
                }
                echo ",";
            endforeach;
        } else {
            foreach ($price_one as $one):
                echo floatval(str_replace(",", "", $one['item_cost'])) . ",";
            endforeach;
        }
      ?>
    ]
  }]
});

// Global variables
let chartType = 'line'; // Default chart type
let originalYAxisStartValue = null; // To store the original y-axis min value

/**
 * Adds a watermark to the chart.
 * The watermark is centered horizontally and updated on window resize.
 * @param {Object} chart - The Highcharts chart instance.
 */
function addWatermark(chart) {
  const watermarkWidth = 650;
  const watermarkHeight = 300;
  let watermark;

  const updateWatermark = () => {
    const chartWidth = chart.plotWidth;
    const chartHeight = chart.plotHeight;

    if (watermark) {
      watermark.destroy(); // Remove any existing watermark
    }

    watermark = chart.renderer.image(
      '<?= base_url("assets/frontend/images/watermark.png") ?>',
      (chartWidth - watermarkWidth) / 2,
      0, // Adjust vertical position if needed
      watermarkWidth,
      watermarkHeight
    ).attr({
      zIndex: -9999,
      style: 'pointer-events:none;opacity:0.7;transform: rotate(0deg);',
      class: 'watermark-image'
    }).add();
  };

  // Add watermark initially and update on window resize
  updateWatermark();
  window.addEventListener("resize", updateWatermark);
}

/**
 * Toggles the chart type between 'line' and 'column' (bar).
 * Updates the series type, marker symbols, and y-axis minimum accordingly.
 */
function toggleChartType() {
  // Determine the new type
  const newType = chartType === 'line' ? 'column' : 'line';
  chartType = newType;

  // Define marker symbols for different chart types
  const symbolOptions = {
    line: 'circle',
    column: 'square'
  };

  // Update the primary series type and marker symbol
  chart.series[0].update({
    type: newType,
    marker: {
      symbol: symbolOptions[newType]
    }
  }, true);

  // Remove additional series if needed (for example, ones with names ending in "(Bar)")
  chart.series.slice(1).forEach(series => {
    if (series.name && series.name.endsWith('(Bar)')) {
      series.remove();
    }
  });

  // Update the y-axis minimum based on the chart type
  if (newType === 'column') {
    chart.yAxis[0].update({
      min: getDefaultYAxisStartValue()
    });
  } else if (originalYAxisStartValue !== null) {
    chart.yAxis[0].update({
      min: originalYAxisStartValue
    });
  }

  chart.redraw();
  // Update the toggle icon's styles
  updateIcon(newType === 'column' ? 'barIcon' : 'lineIcon');
}

/**
 * Calculates a default y-axis starting value based on the current series data.
 * @returns {number} - The calculated y-axis start value.
 */
function getDefaultYAxisStartValue() {
  const priceData = chart.series[0].data.map(point => point.y);
  const minPrice = Math.min(...priceData);
  // Adding a buffer of 2 (adjust as needed)
  return minPrice - 2;
}

/**
 * Updates icon styles by toggling a "selected" class.
 * @param {string} iconId - The ID of the icon to be marked as selected.
 */
function updateIcon(iconId) {
  document.getElementById('lineIcon').classList.remove('selected');
  document.getElementById('barIcon').classList.remove('selected');
  document.getElementById(iconId).classList.add('selected');
}

// Add event listener to toggle between chart types
const toggleButton = document.getElementById('lineToBarToggle');
if (toggleButton) {
  toggleButton.addEventListener('click', toggleChartType);
} else {
  console.error('Element with ID "lineToBarToggle" not found.');
}

// Add event listener for full-screen toggle
const fullScreenButton = document.getElementById('btnFullscreen');
if (fullScreenButton) {
  fullScreenButton.addEventListener('click', () => {
    if (chart && chart.fullscreen) {
      chart.fullscreen.toggle();
    } else {
      console.error('Chart or fullscreen module is not available.');
    }
  });
} else {
  console.error('Element with ID "btnFullscreen" not found.');
}


// ----- Date Formatting Functions -----
const formatMonth = (date) => {
  const options = { year: 'numeric', month: 'short' };
  return new Intl.DateTimeFormat('en-US', options).format(date);
};

const formatYear = (date) => date.getFullYear().toString();

const formatQuarter = (date) => {
  const month = date.getMonth();
  const startMonth = Math.floor(month / 3) * 3;
  const endMonth = startMonth + 2;
  const startMonthName = new Date(date.getFullYear(), startMonth)
    .toLocaleString('default', { month: 'short' });
  const endMonthName = new Date(date.getFullYear(), endMonth)
    .toLocaleString('default', { month: 'short' });
  return `${startMonthName}-${endMonthName} ${date.getFullYear()}`;
};

// ----- Determine if CSV/Excel download is enabled based on session -----
const isExcelDownloadEnabled = <?php echo ($this->session->userdata('weeksd') === "Month" 
    || $this->session->userdata('weeksd') === "Year" 
    || $this->session->userdata('weeksd') === "Quarter") ? 'true' : 'false'; ?>;

// Get the Excel download button and date input elements
const excelDownloadButton = document.getElementById('excelDownloadButton');
const toDateInput = document.getElementById('date_to');
const fromDateInput = document.getElementById('date_from');

if (toDateInput && fromDateInput && toDateInput.value && fromDateInput.value) {
  const toDate = new Date(toDateInput.value);
  const fromDate = new Date(fromDateInput.value);

  if (isExcelDownloadEnabled && excelDownloadButton) {
    excelDownloadButton.addEventListener('click', () => {
      // Build CSV header using only commodity series (excluding average/trendline series)
      let csvContent = "data:text/csv;charset=utf-8,";
      csvContent += "Date,";

      // Filter out series that are flagged as average or trendline
      const validSeries = chart.series.filter(series => 
        !series.options.isTrendline && !series.options.isAverage
      );
      if (validSeries.length > 0) {
        csvContent += validSeries[0].name;
      }
      csvContent += "\n";

      // Process chart categories (assumed to be date strings) and filter by date range
      const categories = chart.xAxis[0].categories;
      let filteredData = [];

      categories.forEach((category, i) => {
        const date = new Date(category);
        let includeData = false;
        let formattedDate = "";

        // For "Year" mode, compare only the year portions
        if (<?php echo ($this->session->userdata('weeksd') === "Year") ? 'true' : 'false'; ?>) {
          const categoryYear = date.getFullYear();
          const fromYear = fromDate.getFullYear();
          const toYear = toDate.getFullYear();
          if (categoryYear >= fromYear && categoryYear <= toYear) {
            formattedDate = formatYear(date);
            includeData = true;
          }
        } else {
          // For "Month" or "Quarter" mode, compare full dates (inclusive)
          if (date >= fromDate && date <= toDate) {
            if (<?php echo ($this->session->userdata('weeksd') === "Quarter") ? 'true' : 'false'; ?>) {
              formattedDate = formatQuarter(date);
            } else if (<?php echo ($this->session->userdata('weeksd') === "Month") ? 'true' : 'false'; ?>) {
              formattedDate = formatMonth(date);
            }
            includeData = true;
          }
        }

        if (includeData) {
          // Build a row with the formatted date and corresponding series values
          const row = { date: formattedDate, data: [] };
          chart.series.forEach((series) => {
            if (!series.options.isTrendline && !series.options.isAverage && row.data.length < 1) {
              row.data.push(series.data[i]?.y || '');
            }
          });
          filteredData.push(row);
        }
      });

      // Limit data to the last 12 entries
      filteredData = filteredData.slice(-12);

      // Append each row to CSV content
      filteredData.forEach((row) => {
        csvContent += `${row.date},${row.data.join(",")}\n`;
      });

      // Create a temporary link element and trigger the CSV download
      const encodedUri = encodeURI(csvContent);
      const link = document.createElement("a");
      link.setAttribute("href", encodedUri);
      link.setAttribute("download", `${chart.title.textStr || 'chart_data'}.csv`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });
  } else if (excelDownloadButton) {
    excelDownloadButton.addEventListener('click', () => {
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: "Excel data is only available for monthly, quarterly, or yearly selection.",
        showCloseButton: true
      });
    });
  }
} else {
  console.error('FROM or TO date input not found or empty.');
}
</script>
<?php } ?>
<!--  update the function to download pdf of current page by rajdeep kaur 01-04-2024 -->
<script src="https://cdn.jsdelivr.net/npm/canvg/dist/browser/canvg.min.js"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<script>
// Generate PDF with chart image and watermark
function generatePdf(commodityName) {
  const doc = new jsPDF('landscape');

  // Adds an image (chart) to the PDF document
  const addChartImage = (chartImage) => {
    // Adjust positioning and dimensions as needed
    doc.addImage(chartImage, 'JPEG', 0, 0, 377, 210);
  };

  // Renders the entire page to a canvas, converts it to an image, and adds it to the PDF
  const renderPageContentToCanvas = () => {
    html2canvas(document.body, { scale: 2 })
      .then(canvas => {
        const pageImage = canvas.toDataURL('image/jpeg');
        addChartImage(pageImage);
        addWatermarkToPdf();
      })
      .catch(err => console.error('Error rendering canvas:', err));
  };

  // Creates a watermark image using a canvas and returns its data URL
  const createWatermarkCanvas = () => {
    const watermarkCanvas = document.createElement('canvas');
    watermarkCanvas.width = 650;
    watermarkCanvas.height = 300;
    const ctx = watermarkCanvas.getContext('2d');

    // Set watermark font and style with some transparency
    ctx.font = '55px Algerian';
    ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
    ctx.textBaseline = 'middle';
    ctx.textAlign = 'center';

    // Center and rotate the text (rotate -30° here)
    ctx.translate(watermarkCanvas.width / 2, watermarkCanvas.height / 2);
    ctx.rotate(-Math.PI / 6);
    ctx.fillText('Costmasters', 0, 0);

    return watermarkCanvas.toDataURL('image/png');
  };

  // Adds the watermark to every page of the PDF and then saves the file
  const addWatermarkToPdf = () => {
    const totalPages = doc.internal.getNumberOfPages();
    const watermarkImage = createWatermarkCanvas();
    for (let i = 1; i <= totalPages; i++) {
      doc.setPage(i);
      doc.addImage(watermarkImage, 'PNG', 40, 40, 280, 55);
    }
    doc.save(`${commodityName}.pdf`);
  };

  // Start rendering the page content and generating the PDF
  renderPageContentToCanvas();
}

// Functions to show/hide a PDF loader using jQuery
const showLoader = () => $('#pdfLoader').show();
const hideLoader = () => $('#pdfLoader').hide();

// Event listener for generating PDF when the print button is clicked
document.getElementById('printPdfBtn').addEventListener('click', () => {
  // Uncomment if you want to show the loader:
  // showLoader();

  // Check if a Highcharts chart is ready
  if (Highcharts.charts.length > 0 && Highcharts.charts[0].renderTo) {
    let commodityName;
    <?php if (isset($commodityTwo) && !empty($commodityTwo)): ?>
      commodityName = '<?php echo $commodity; ?> - <?php echo $commodityTwo; ?>';
    <?php else: ?>
      commodityName = '<?php echo $commodity; ?>';
    <?php endif; ?>

    generatePdf(commodityName);
  } else {
    console.error("Highcharts chart not ready.");
    hideLoader();
  }

  hideLoader();
});

// Event listener for downloading a manual PDF when the 'manual_book' button is clicked
document.getElementById('manual_book').addEventListener('click', () => {    
  const link = document.createElement('a');
  link.href = '<?= base_url() ?>assets/frontend/files/RMPTS -User Manual.pdf'; // Update with your actual file path
  link.download = 'RMPTS -User Manual.pdf';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
});

</script>
<!-- bar graph chart by rajdeep on 29-04-2024 -->
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<script>
function generateChart(containerId, data, isYearData) {
  var avgPrices, categories;

  // Helper function to check if all elements in an array are zero
  function allZeros(arr) {
    return arr.every(price => parseFloat(price) === 0);
  }

  // Helper function to check if any element in an array is non-zero
  function hasUpcomingValues(arr) {
    return arr.some(price => parseFloat(price) > 0);
  }

  // Data selection logic
  if (data && data.avg_price_commodity && data.avg_price_commodityTwo) {
    var allZerosCommodityOne = allZeros(data.avg_price_commodity);
    var allZerosCommodityTwo = allZeros(data.avg_price_commodityTwo);

    if (allZerosCommodityOne && allZerosCommodityTwo) return;

    var commodityOneUpcoming = hasUpcomingValues(data.avg_price_commodity);
    var commodityTwoUpcoming = hasUpcomingValues(data.avg_price_commodityTwo);

    if (commodityOneUpcoming && !commodityTwoUpcoming) {
      avgPrices = data.avg_price_commodity;
    } else if (!commodityOneUpcoming && commodityTwoUpcoming) {
      avgPrices = data.avg_price_commodityTwo;
    } else {
      avgPrices = isYearData ? data.avg_price_commodity : data.avg_price_commodityTwo;
    }
    categories = isYearData ? data.year : data.month.map(month => month.slice(0, 3));
  } else if (data && data.avg_price_commodity) {
    if (allZeros(data.avg_price_commodity)) return;
    avgPrices = data.avg_price_commodity;
    categories = isYearData ? data.year : data.month.map(month => month.slice(0, 3));
  } else if (data && data.avg_price_commodityTwo) {
    if (allZeros(data.avg_price_commodityTwo)) return;
    avgPrices = data.avg_price_commodityTwo;
    categories = isYearData ? data.year : data.month.map(month => month.slice(0, 3));
  } else {
    return;
  }

  // Process and round prices
  avgPrices = avgPrices.map(price => parseFloat(price).toFixed(1)).map(parseFloat);

  // Calculate average price
  var avgPrice = avgPrices.reduce((total, amount) => total + amount) / avgPrices.length;

  // Determine rounding factor based on average price
  var roundFactor = avgPrice >= 1000000 ? 1000000 
                 : avgPrice >= 100000 ? 100000 
                 : avgPrice >= 10000 ? 10000 
                 : avgPrice >= 1000 ? 1000 
                 : 10;

  // Determine y-axis bounds
  var yAxisMin = Math.floor(Math.min(...avgPrices) / roundFactor) * roundFactor - 2;
  var yAxisMax = Math.ceil(Math.max(...avgPrices) / roundFactor) * roundFactor + 2;

  // Chart options
  var options = {
    series: [{
      name: isYearData ? 'Year Analysis' : 'Month Analysis',
      data: avgPrices,
    }],
    chart: {
      height: 190,
      maxHeight: 190,
      type: 'bar',
      toolbar: { show: false }
    },
    plotOptions: {
      bar: {
        horizontal: false,
        columnWidth: '60%',
        endingShape: 'flat',
        distributed: true,
        barHeight: '80%',
      }
    },
    colors: ['#008FFB', '#00E396', '#FEB019'],
    dataLabels: {
      enabled: true,
      position: 'top',
      offsetY: '5%',
      style: {
        fontSize: '10px',
        colors: ["#304758"]
      }
    },
    xaxis: {
      categories: categories,
      labels: { show: false, style: { fontSize: '10px' } },
      axisBorder: { show: false },
      axisTicks: { show: false },
      crosshairs: {
        fill: {
          type: 'gradient',
          gradient: {
            colorFrom: '#D8E3F0',
            colorTo: '#BED1E6',
            stops: [0, 100],
            opacityFrom: 0.4,
            opacityTo: 0.5,
          }
        }
      }
    },
    yaxis: {
      min: yAxisMin,
      max: yAxisMax,
      tickAmount: 5,
      axisBorder: { show: false },
      axisTicks: { show: false },
      labels: {
        show: true,
        formatter: val => (val)
      }
    },
    title: {
      text: isYearData ? 'YOY analysis' : 'MOM analysis',
      align: 'center',
      offsetX: 0,
      offsetY: 15,
      style: { color: '#444', fontSize: "12px" }
    },
    tooltip: {
      enabled: true,
      fixed: { enabled: true, position: 'topRight', offsetX: 0, offsetY: 0 },
      style: { fontSize: '12px' },
      x: { show: true, format: 'dd MMM', formatter: undefined },
      y: { formatter: undefined, title: { formatter: seriesName => seriesName } },
      marker: { show: true },
    },
    legend: { fontSize: '9px' }
  };

  var chart = new ApexCharts(document.querySelector(containerId), options);
  chart.render();
}

// Your data
var MonthlycommodityData = <?php echo json_encode($average_price_for_three_months); ?>;
var YearlycommodityData = <?php echo json_encode($average_price_for_three_years); ?>;

// Generate charts for the first commodity
generateChart("#myChart", {
  avg_price_commodity: MonthlycommodityData.avg_price_commodity,
  month: MonthlycommodityData.month
}, false);
generateChart("#myChart1", {
  avg_price_commodity: YearlycommodityData.avg_price_commodity,
  year: YearlycommodityData.year
}, true);

// Generate charts for the second commodity
generateChart("#myChartMonthCommodityTwo", {
  avg_price_commodity: MonthlycommodityData.avg_price_commodityTwo,
  month: MonthlycommodityData.month
}, false);
generateChart("#myChartYearCommodityTwo", {
  avg_price_commodity: YearlycommodityData.avg_price_commodityTwo,
  year: YearlycommodityData.year
}, true);

// Repeat for the PUP charts
generateChart("#myChartPUP", {
  avg_price_commodity: MonthlycommodityData.avg_price_commodity,
  month: MonthlycommodityData.month
}, false);
generateChart("#myChart1PUP", {
  avg_price_commodity: YearlycommodityData.avg_price_commodity,
  year: YearlycommodityData.year
}, true);
generateChart("#myChartMonthCommodityTwoPUP", {
  avg_price_commodity: MonthlycommodityData.avg_price_commodityTwo,
  month: MonthlycommodityData.month
}, false);
generateChart("#myChartYearCommodityTwoPUP", {
  avg_price_commodity: YearlycommodityData.avg_price_commodityTwo,
  year: YearlycommodityData.year
}, true);

//display bar graph on full screen 
document.addEventListener('DOMContentLoaded', function() {
    // Get all modal elements
    var modals = document.querySelectorAll('.modal');
    var openModalBtns = document.querySelectorAll('.open-modal-btn');
    openModalBtns.forEach(function(btn) {
        btn.onclick = function() {
            // Find the corresponding modal by traversing the DOM
            var modal = this.parentNode.querySelector('.modal');
            modal.style.display = 'block';
        };
    });

    // Get all close button elements
    var closeBtns = document.querySelectorAll('.close');
    closeBtns.forEach(function(btn) {
        btn.onclick = function() {
            var modal = this.parentNode.parentNode;
            modal.style.display = 'none';
        };
    });

    // When the user clicks anywhere outside of a modal, close it
    window.onclick = function(event) {
        modals.forEach(function(modal) {
            if (event.target == modal) {
                modal.style.display = 'none';
            }
        });
    };
});

//Disable print page
document.addEventListener('keydown', function(event) {
    if (event.ctrlKey && event.key === 'p') {
        event.preventDefault();
        //alert('Printing is disabled on this page.');
    }
});
</script>