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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/models/
Upload File :
Current File : /home/costmasters.in/www/application/modules/frontend/models/Graph_model.php
<?php

class Graph_model extends CI_Model
{

    public function __construct()
    {
        parent::__construct();
    }

    // commodity head fetch
    public function commodity_head()
    {
        if (!isset($_SESSION['email'])) {
            return []; // Return empty array if session email is not set
        }

        $this->db->where('subscription_register.email', $_SESSION['email']);
        $this->db->select('subscription_register.*, tbl_item_cat.category_name'); // Select only required fields
        $this->db->join('tbl_item_cat', 'tbl_item_cat.id = subscription_register.choose_type', 'left'); 
        $query = $this->db->get('subscription_register');

        return ($query->num_rows() > 0) ? $query->result_array() : []; // Ensure result handling
    }

    private function getCommodityHead()
    {
        $head = isset($_SESSION['commodity_head']) ? $_SESSION['commodity_head'] : '';
        return $head;
    }

    private function get_head($commodity_head)
    {
        return empty($commodity_head) ? $_SESSION['commodity_head'] : $commodity_head;
    }

    // commodity dependent on commodity head
    public function commodity()
    {
        // Get data from AJAX request
        $item_name = $this->input->post('commodity_head');
        $allowed_items = $this->input->post('allowed_items');

        // Initialize output variable
        $output = '';  

        // Step 1: Get category_id from tbl_item_cat
        $this->db->select('id');
        $this->db->from('tbl_item_cat');
        $this->db->where('category_name', $item_name);
        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            $category_id = $query->row()->id;

            // Step 2: Fetch commodities from category_items
            $this->db->select('id, item_name'); 
            $this->db->from('category_items');
            $this->db->where('category_id', $category_id);

            if (!empty($allowed_items)) {
                $allowed_items_array = explode(',', $allowed_items); 
                $this->db->where_in('id', $allowed_items_array);
            }

            $this->db->order_by('item_name', 'ASC');
            $commodity_query = $this->db->get();

            if ($commodity_query->num_rows() > 0) {
                foreach ($commodity_query->result() as $row) {
                    $output .= '<option data-id="' . $row->id . '" value="' . $row->item_name . '">' . $row->item_name . '</option>';
                }
            } else {
                $output = '<option value="">No commodities found</option>';
            }
        } else {
            $output = '<option value="">No category found</option>';
        }

        echo $output; // Ensure $output is always echoed
    }

    function graph($start, $end, $commodity)
    {
        // Validate that the required parameters are provided.
        if (empty($start) || empty($end) || empty($commodity)) {
            // You can decide to return an empty result or handle the error differently.
            return [];
        }

        // Optional: Validate the date format if needed.
        // For example, using DateTime::createFromFormat() to check if dates are valid.
        $startDate = date_create_from_format('Y-m-d', $start);
        $endDate   = date_create_from_format('Y-m-d', $end);
        if (!$startDate || !$endDate) {
            return []; // Or handle the error as required.
        }

        // Build the query using query builder's built-in parameter binding for safety.
        $this->db->select('*'); // Replace '*' with specific columns if needed.
        $this->db->from('chart_item');
        $this->db->where('date(chart_date) >=', $start);
        $this->db->where('date(chart_date) <=', $end);
        $this->db->where('chart_item_name', $commodity);

        $query = $this->db->get();

        return $query->result();
    }
    
    function end_date($end, $commodity)
    {
        // Validate inputs to avoid unnecessary queries.
        if (empty($end) || empty($commodity)) {
            return [];
        }

        // Optionally, validate the date format (e.g., 'Y-m-d').
        $date = DateTime::createFromFormat('Y-m-d', $end);
        if (!$date || $date->format('Y-m-d') !== $end) {
            return []; // Or handle the error as needed.
        }

        // Build the query using CodeIgniter's query builder.
        $this->db->select('*');  // Consider specifying only needed columns.
        $this->db->from('chart_item');
        // Use the query builder's parameter binding for safety.
        $this->db->where('date(chart_date)', $end);
        $this->db->where('chart_item_name', $commodity);
        
        $query = $this->db->get();
        return $query->result_array();
    }

    function graphTwo($start, $end, $commodity, $commodityTwo)
    {
        // Validate inputs early
        if (empty($start) || empty($end) || empty($commodity) || empty($commodityTwo)) {
            return []; // Optionally handle error/return message as needed.
        }

        // Build the query using query builder
        $this->db->select('*');  // Consider selecting only required columns for better performance.
        $this->db->from('chart_item');
        
        // Date conditions: using query builder's parameter binding
        $this->db->where('date(chart_date) >=', $start);
        $this->db->where('date(chart_date) <=', $end);
        
        // Group commodity conditions so the date condition applies to both
        $this->db->group_start();
            $this->db->where('chart_item_name', $commodity);
            $this->db->or_where('chart_item_name', $commodityTwo);
        $this->db->group_end();
        
        $query = $this->db->get();
        return $query->result();
    }

    public function get_price_exis($commodity_head, $commodity_name)
    {
        $sql = "
            SELECT DISTINCT 
                chart_price_unit, 
                chart_exis_duty 
            FROM 
                chart_item  
            WHERE 
                chart_cat_id = ? 
                AND chart_item_name = ? 
            LIMIT 1
        ";
        
        $query = $this->db->query($sql, [$commodity_head, $commodity_name]);
        $array = $query->result_array();
        return $array;
    }

    public function chart_date($start, $end, $commodity)
    {
        // Validate inputs
        if (empty($start) || empty($end) || empty($commodity)) {
            return []; // Return empty array if any parameter is missing
        }

        $second_commodity = $this->input->post('commodityTwo', true);

        // Ensure commodities are stored as an array
        $commodities = [$commodity];
        if (!empty($second_commodity)) {
            $commodities[] = $second_commodity;
        }

        $this->db->select('*');
        $this->db->from('chart_item');
        $this->db->where('chart_date >=', date('Y-m-d', strtotime($start))); // Ensure proper date format
        $this->db->where('chart_date <=', date('Y-m-d', strtotime($end))); 
        $this->db->where_in('chart_item_name', $commodities);
        $this->db->order_by('chart_date', 'ASC');

        $query = $this->db->get();
        return $query->result_array();
    }

    public function get_price_data($start, $end, $commodity, $head = null)
    {
        $sql = "
            SELECT 
                chart_date,
                CAST(MAX(chart_item_cost) AS DECIMAL(10,1)) AS max_cost,
                CAST(MIN(chart_item_cost) AS DECIMAL(10,1)) AS min_cost,
                CAST(AVG(chart_item_cost) AS DECIMAL(10,1)) AS avg_cost,
                CAST(chart_item_cost AS DECIMAL(10,1)) AS item_cost
            FROM 
                chart_item 
            WHERE 
                chart_item_name = ?
        ";

        $params = [$commodity];

        if (!empty($head)) {
            $sql .= " AND chart_cat_id = ?";
            $params[] = $head;
        }

        $sql .= " AND chart_date BETWEEN ? AND ?
                  GROUP BY chart_date 
                  ORDER BY chart_date ASC";

        $params[] = $start;
        $params[] = $end;

        $query = $this->db->query($sql, $params);
        return $query->result_array();
    }

    public function week_date($start, $end, $commodity)
    {
        $second_commodity = $_POST['commodityTwo'] ?? '';

        $commodities = [$commodity];
        if (!empty($second_commodity)) {
            $commodities[] = $second_commodity;
        }

        // Generate placeholders for commodity array
        $placeholders = implode(',', array_fill(0, count($commodities), '?'));

        $query = $this->db->query(
            "SELECT 
                YEARWEEK(chart_date, 1) AS week_number,  -- Get ISO week number (Monday start)
                MAX(chart_date) AS chart_date,    -- Get the last date of that week
                chart_item_name
            FROM chart_item 
            WHERE chart_date BETWEEN ? AND ? 
            AND chart_item_name IN ($placeholders)
            GROUP BY YEARWEEK(chart_date, 1), chart_item_name
            ORDER BY chart_date ASC",
            array_merge([$start, $end], $commodities)
        );

        return $query->result_array();
    }

    public function week_start_date($start, $end, $commodity)
    {
        $sql = "
            SELECT 
                WEEK(chart_date) AS week_num,
                MIN(chart_date) AS chart_date,
                chart_item_name,
                ROUND(MIN(chart_item_cost), 1) AS min_cost,
                ROUND(MAX(chart_item_cost), 1) AS max_cost,
                ROUND(AVG(chart_item_cost), 1) AS avg_cost
            FROM 
                chart_item
            WHERE 
                chart_date BETWEEN ? AND ?
                AND chart_item_name = ?
            GROUP BY 
                CEIL(WEEK(chart_date)), YEAR(chart_date)
            ORDER BY 
                chart_date ASC
            LIMIT 1
        ";

        $query = $this->db->query($sql, [$start, $end, $commodity]);
        return $query->row_array();
    }

    public function week_end_date($end, $commodity)
    {
        $sql = "
            SELECT
                YEARWEEK(chart_date, 1)   AS year_week,  -- combines YEAR+WEEK in one integer
                MIN(chart_item_cost)       AS min_cost,
                MAX(chart_item_cost)       AS max_cost,
                AVG(chart_item_cost)       AS avg_cost
            FROM
                chart_item
            WHERE
                chart_date      = ?
                AND chart_item_name = ?
            LIMIT 1
        ";

        return $this->db
                    ->query($sql, [$end, $commodity])
                    ->row_array();  // fetches a single row instead of result_array()
    }

    public function week_price_one($start, $end, $commodity)
    {
        $head = $_SESSION['commodity_head'];
        
        $query = $this->db->query("
            SELECT 
                WEEK(chart_date) AS date1, 
                DATE_ADD(chart_date, INTERVAL (6 - WEEKDAY(chart_date)) DAY) AS chart_date, 
                CAST(AVG(chart_item_cost) AS DECIMAL(10,1)) AS chart_item_cost2, 
                CAST(MAX(chart_item_cost) AS DECIMAL(10,1)) AS max_cost, 
                CAST(MIN(chart_item_cost) AS DECIMAL(10,1)) AS min_cost 
            FROM chart_item 
            WHERE chart_item_name = ?  
            AND chart_cat_id = ? 
            AND chart_date BETWEEN ? AND ? 
            GROUP BY YEAR(chart_date), WEEK(chart_date) 
            ORDER BY chart_date ASC", [$commodity, $head, $start, $end]
        );

        return $query->result_array();
    }

    public function week_end_price_one($end, $commodity)
    {
        $query = $this->db->query("select week (chart_date) date1 ,chart_date, AVG (chart_item_cost) as chart_item_cost, round(MIN(chart_item_cost),1) as min_cost, round(MAX(chart_item_cost),1) as max_cost, round( avg( `chart_item_cost`), 1 ) AS chart_item_cost2 from chart_item where (chart_item_name='$commodity') and chart_date = '$end' GROUP BY CEIL(WEEK(chart_date)) ,YEAR(chart_date) order by chart_date ASC");
        $array = $query->result_array();
        return $array;
    }

    public function week_price_two($start, $end, $commodityTwo)
    {
       $sql = "SELECT 
                    WEEK(chart_date, 1) AS date1,
                    DATE_ADD(chart_date, INTERVAL(1 - WEEKDAY(chart_date)) DAY) AS chart_date, 
                    CAST(AVG(chart_item_cost) AS DECIMAL(10,1)) AS chart_item_cost2,
                    CAST(MAX(chart_item_cost) AS DECIMAL(10,1)) AS max_cost,
                    CAST(MIN(chart_item_cost) AS DECIMAL(10,1)) AS min_cost
                FROM chart_item
                WHERE chart_item_name = ? 
                    AND chart_date BETWEEN ? AND ?
                GROUP BY YEAR(chart_date), WEEK(chart_date, 1), chart_date
                ORDER BY  chart_date ASC";

        $query = $this->db->query($sql, [$commodityTwo, $start, $end]);

        return $query->result_array(); // Returning result as an array
    }
 

    public function week_end_price_two($end, $commodityTwo)
    {
        $query = $this->db->query("select week (chart_date) date1 ,chart_date, AVG (chart_item_cost) as chart_item_cost, round(MIN(chart_item_cost),1) as min_cost, round(MAX(chart_item_cost),1) as max_cost, round( avg( `chart_item_cost`), 1 ) AS chart_item_cost2 from chart_item where (chart_item_name='$commodityTwo') and chart_date = '$end' GROUP BY CEIL(WEEK(chart_date)) ,YEAR(chart_date) order by chart_date ASC");
        $array = $query->result_array();
        return $array;
    }

    public function month_date($start, $end, $commodity)
    {
        $second_commodity = isset($_POST['commodityTwo']) ? $_POST['commodityTwo'] : '';
        $commodity_query = "";
        if (!empty ($second_commodity)) {
            $commodity_query = " OR chart_item_name = '$second_commodity'";
        }
        $query = $this->db->query("SELECT *, MAX(chart_date) AS chart_date  FROM `chart_item` WHERE chart_date BETWEEN '$start' AND '$end' and (chart_item_name = '$commodity' $commodity_query) group by Year(`chart_date`), month(`chart_date`) ");
        $array = $query->result_array();
        return $array;
    }

    public function month_start_date($start, $end, $commodity)
    {
        $query = $this->db->query("SELECT *, AVG(`chart_item_cost`) as chart_item_cost , chart_price_unit,  round(avg( `chart_item_cost` ) , 1 ) AS avg_cost, round(min( `chart_item_cost` ) , 1 ) AS min_cost, round(max( `chart_item_cost` ) , 1 ) AS max_cost  FROM `chart_item` WHERE chart_date BETWEEN '$start' AND '$end' and chart_item_name ='$commodity'  group by Year(`chart_date`), month(`chart_date`) ");
        $array = $query->row_array();
        // print_r($array);die;
        return $array;
    }

    public function month_end_date($end, $commodity)
    {
        $query = $this->db->query("SELECT *, AVG(`chart_item_cost`) as chart_item_cost , chart_price_unit,  round(avg( `chart_item_cost` ) , 1 ) AS chart_item_cost2, round(min( `chart_item_cost` ) , 1 ) AS min_cost, round(max( `chart_item_cost` ) , 1 ) AS max_cost  FROM `chart_item` WHERE chart_date = '$end' and chart_item_name ='$commodity'  group by Year(`chart_date`), month(`chart_date`) ");
        $array = $query->result_array();
        return $array;
    }
  
    public function month_price_one_year($start, $end, $commodity_head, $commodity)
    {
        $head = $this->get_head($commodity_head);

        $query = $this->db->query("
            SELECT *, 
                   CAST(SUM(CAST(chart_item_cost AS FLOAT)) / COUNT(chart_item_cost) AS DECIMAL(10,2)) AS chart_item_cost2, 
                   CAST(MAX(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,2)) AS max_cost, 
                   CAST(MIN(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,2)) AS min_cost 
            FROM `chart_item` 
            WHERE chart_item_name = ? 
              AND chart_cat_id = ? 
              AND chart_date BETWEEN ? AND ? 
            GROUP BY YEAR(chart_date), MONTH(chart_date)
        ", [$commodity, $head, $start, $end]);

        return $query->result_array();
    }

    public function month_price_one($start, $end, $commodity_head, $commodity)
    {
        $head = $this->get_head($commodity_head);

        $sql = "SELECT *, LAST_DAY(chart_date) AS chart_date, 
                       CAST(AVG(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS chart_item_cost2, 
                       CAST(MAX(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS max_cost, 
                       CAST(MIN(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS min_cost 
                FROM `chart_item` 
                WHERE chart_item_name = ?  
                AND `chart_cat_id` = ? 
                AND chart_date BETWEEN ? AND ? 
                GROUP BY YEAR(`chart_date`), MONTH(`chart_date`)";

        $query = $this->db->query($sql, [$commodity, $head, $start, $end]);
        return $query->result_array();
    }

    public function month_end_price_one($end, $commodity)
    {
        $query = $this->db->query("SELECT `chart_date` , AVG(`chart_item_cost`) as chart_item_cost , chart_price_unit,  round(avg( `chart_item_cost` ) , 1 ) AS chart_item_cost2, round(min( `chart_item_cost` ) , 1 ) AS min_cost, round(max( `chart_item_cost` ) , 1 ) AS max_cost FROM `chart_item` WHERE chart_item_name = '$commodity' AND chart_date = '$end' group by Year(`chart_date`) , month(`chart_date`) ");
        $array = $query->result_array();
        return $array;
    }

    public function month_price_two($start, $end, $commodity)
    {
        $sql = "SELECT *, LAST_DAY(chart_date) AS chart_date, 
                       CAST(AVG(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS chart_item_cost2, 
                       CAST(MAX(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS max_cost, 
                       CAST(MIN(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS min_cost 
                FROM `chart_item` 
                WHERE chart_item_name = ?  
                AND chart_date BETWEEN ? AND ? 
                GROUP BY YEAR(`chart_date`), MONTH(`chart_date`)";

        $query = $this->db->query($sql, [$commodity, $start, $end]);
        return $query->result_array();
    }

    public function year_date($start, $end, $commodity)
    {
        $head = $this->get_head($commodity);
        $second_commodity = isset($_POST['commodityTwo']) ? $_POST['commodityTwo'] : '';
        $commodity_query = "";
        if (!empty ($second_commodity)) {
            $commodity_query = " OR chart_item_name = '$second_commodity'";
        }
        $query = $this->db->query("SELECT *, MAX(chart_date) AS chart_date FROM chart_item where chart_date between '$start' and '$end' and (chart_item_name = '$head' $commodity_query)  GROUP BY YEAR(`chart_date`)");
        $array = $query->result_array();
        return $array;
    }

    public function year_start_date($start, $end, $commodity)
    {
        $query = $this->db->query("SELECT *, AVG(`chart_item_cost`) as chart_item_cost, chart_price_unit, round(avg( `chart_item_cost` ), 1 ) AS avg_cost, round(min( `chart_item_cost` ) , 1 ) AS min_cost, round(max( `chart_item_cost` ) , 1 ) AS max_cost FROM chart_item where chart_date between '$start' and '$end' and chart_item_name='$commodity' GROUP BY YEAR(`chart_date`)");
        $array = $query->row_array();
        return $array;
    }

    public function year_end_date($end, $commodity)
    {
        $query = $this->db->query("SELECT *, AVG(`chart_item_cost`) as chart_item_cost, chart_price_unit, round(avg( `chart_item_cost` ), 1 ) AS chart_item_cost, round(min( `chart_item_cost` ) , 1 ) AS min_cost, round(max( `chart_item_cost` ) , 1 ) AS max_cost FROM chart_item where chart_date = '$end' and chart_item_name='$commodity' GROUP BY YEAR(`chart_date`)");
        $array = $query->result_array();
        return $array;
    }

public function get_current_year_data($end, $commodity)
{
    // --- 1) Compute all the date‐ranges upfront (no YEAR()/MONTH() in SQL) ---
    $selectedYear       = (int) date('Y',   strtotime($end));
    $selectedYearStart  = "{$selectedYear}-01-01";
    $selectedYearEnd    = "{$selectedYear}-12-31";
    $previousYear       = $selectedYear - 1;
    $previousYearStart  = "{$previousYear}-01-01";
    $previousYearEnd    = "{$previousYear}-12-31";

    $selectedMonthStart = date('Y-m-01',      strtotime($end));
    $selectedMonthEnd   = date('Y-m-t',       strtotime($end));
    $prevMonthFirstDay  = date('Y-m-01',      strtotime("$end -1 month"));
    $previousMonthStart = $prevMonthFirstDay;
    $previousMonthEnd   = date('Y-m-t',       strtotime($prevMonthFirstDay));
    
    // (optional) include your category filter to use that composite index
    $head = $this->session->userdata('commodity_head') ?? null;

    // --- 2) Build one SQL with CASE…WHEN for each period’s aggregates ---
    $sql = "
        SELECT
            CAST(AVG(CASE WHEN chart_date BETWEEN ? AND ? THEN chart_item_cost END) AS DECIMAL(10,1)) AS current_year_avg,
            CAST(MIN(CASE WHEN chart_date BETWEEN ? AND ? THEN chart_item_cost END) AS DECIMAL(10,1)) AS current_year_min,
            CAST(MAX(CASE WHEN chart_date BETWEEN ? AND ? THEN chart_item_cost END) AS DECIMAL(10,1)) AS current_year_max,
            CAST(AVG(CASE WHEN chart_date BETWEEN ? AND ? THEN chart_item_cost END) AS DECIMAL(10,1)) AS previous_year_avg,
            CAST(MIN(CASE WHEN chart_date BETWEEN ? AND ? THEN chart_item_cost END) AS DECIMAL(10,1)) AS previous_year_min,
            CAST(MAX(CASE WHEN chart_date BETWEEN ? AND ? THEN chart_item_cost END) AS DECIMAL(10,1)) AS previous_year_max,
            CAST(AVG(CASE WHEN chart_date BETWEEN ? AND ? THEN chart_item_cost END) AS DECIMAL(10,1)) AS current_month_avg,
            CAST(AVG(CASE WHEN chart_date BETWEEN ? AND ? THEN chart_item_cost END) AS DECIMAL(10,1)) AS previous_month_avg
        FROM chart_item
        WHERE chart_item_name = ?
        " . ($head ? "AND chart_cat_id = ?\n" : "") . "
          AND chart_date BETWEEN ? AND ?  -- from start of prev year to end of this year
    ";

    // --- 3) Bind parameters in the exact order of the placeholders above ---
    $params = [
        // current year (avg, min, max)
        $selectedYearStart, $selectedYearEnd,
        $selectedYearStart, $selectedYearEnd,
        $selectedYearStart, $selectedYearEnd,

        // previous year (avg, min, max)
        $previousYearStart, $previousYearEnd,
        $previousYearStart, $previousYearEnd,
        $previousYearStart, $previousYearEnd,

        // current month
        $selectedMonthStart, $selectedMonthEnd,

        // previous month
        $previousMonthStart, $previousMonthEnd,

        // commodity filter
        $commodity,
    ];

    if ($head) {
        $params[] = $head;
    }

    // global date‐range for index usage
    $params[] = $previousYearStart;
    $params[] = $selectedYearEnd;

    // --- 4) Execute once and fetch the single row ---
    $row = $this->db->query($sql, $params)->row_array();

    // --- 5) Post‑process differences & percentages in PHP ---
    $cyAvg = (float) ($row['current_year_avg']  ?? 0);
    $cyMin = (float) ($row['current_year_min']  ?? 0);
    $cyMax = (float) ($row['current_year_max']  ?? 0);
    $pmAvg = (float) ($row['previous_month_avg'] ?? 0);
    $cmAvg = (float) ($row['current_month_avg']  ?? 0);

    $monthDiff       = $pmAvg - $cmAvg;
    $monthPct        = $pmAvg
        ? ($monthDiff / $pmAvg) * 100
        : 0;

    return [
        'current_month_avg'      => number_format($cmAvg, 1),
        'previous_month_avg'     => number_format($pmAvg, 1),
        'current_year_avg'       => number_format($cyAvg, 1),
        'current_year_min'       => number_format($cyMin, 1),
        'current_year_max'       => number_format($cyMax, 1),

        'average_price_difference' => number_format($cyAvg - $cmAvg, 1),
        'max_price_difference'     => number_format($cyMax - $cmAvg, 1),
        'min_price_difference'     => number_format($cyMin - $cmAvg, 1),

        'average_price_percentage' => $cmAvg
            ? number_format((($cyAvg - $cmAvg) / $cmAvg) * 100, 1)
            : '0.0',
        'max_price_percentage'     => $cmAvg
            ? number_format((($cyMax - $cmAvg) / $cmAvg) * 100, 1)
            : '0.0',
        'min_price_percentage'     => $cmAvg
            ? number_format((($cyMin - $cmAvg) / $cmAvg) * 100, 1)
            : '0.0',

        'month_price_difference'  => number_format($monthDiff, 1),
        'month_price_percentage'  => number_format($monthPct, 1),
    ];
}


    public function get_current_year_data_two($end,$commodityTwo)
    {
        // Get the current year and month
        $current_year = date('Y');
        $selected_year = date('Y', strtotime($end)); // Extract the year from the selected date
        $selected_month = date('m', strtotime($end));
        $previous_month = date('m', strtotime(date('Y-m-01', strtotime($end)) . ' -1 month'));  // Get the month of the previous month
        $previous_year = date('Y', strtotime('-1 year'));
        $month_price_percentage = 0;
        $min_price_percentage = 0;
        $max_price_percentage = 0;
        $average_price_percentage = 0;

        // Query to retrieve data for the current year
        $this->db->select("AVG(`chart_item_cost`) AS current_year_avg, 
                            MIN(`chart_item_cost`) AS current_year_min, 
                            MAX(`chart_item_cost`) AS current_year_max");
        $this->db->from("chart_item");
        $this->db->where("YEAR(chart_date)", $selected_year);
        $this->db->where("chart_item_name", $commodityTwo);
        $query_year = $this->db->get();
        $current_year_data = $query_year->row_array();
     //  echo $this->db->last_query();
       // print_r($current_year_data); die;
        // Query to retrieve data for the previous year
        $this->db->select("AVG(`chart_item_cost`) AS previous_year_avg, 
                            MIN(`chart_item_cost`) AS previous_year_min, 
                            MAX(`chart_item_cost`) AS previous_year_max");
        $this->db->from("chart_item");
        $this->db->where("YEAR(chart_date)", $previous_year);
        $this->db->where("chart_item_name", $commodityTwo);
        $query_previous_year = $this->db->get();
        $previous_year_data = $query_previous_year->row_array();

       // Query to retrieve data for the selected month 
        $this->db->select("AVG(`chart_item_cost`) AS current_month_avg");
        $this->db->from("chart_item");
        $this->db->where("YEAR(chart_date)", $selected_year);
        $this->db->where("MONTH(chart_date)", $selected_month);
        $this->db->where("chart_item_name", $commodityTwo);
        $query_month = $this->db->get();
        $current_month_data = $query_month->row_array();

        // Query to retrieve data for the previous month 
        $this->db->select("AVG(`chart_item_cost`) AS previous_month_avg");
        $this->db->from("chart_item");
        $this->db->where("YEAR(chart_date)", $selected_year);
        $this->db->where("MONTH(chart_date)", $previous_month);
        $this->db->where("chart_item_name", $commodityTwo);
        $query_previous_month = $this->db->get();
        $previous_month_data = $query_previous_month->row_array();

        // Calculate differences and percentages
       $month_price_difference = isset($current_month_data['current_month_avg']) && isset($previous_month_data['previous_month_avg']) ? $previous_month_data['previous_month_avg'] - $current_month_data['current_month_avg'] : 0;
        if (isset($current_month_data['current_month_avg']) && isset($previous_month_data['previous_month_avg']) &&
            $current_month_data['current_month_avg'] != 0 && $previous_month_data['previous_month_avg'] != 0) {    
            // Calculate the month price percentage
            $month_price_percentage = ($month_price_difference / $previous_month_data['previous_month_avg']) * 100;
        }

        // Prepare the result array
        $result = [
            'current_month_avg' => isset($current_month_data['current_month_avg']) ? number_format(floatval($current_month_data['current_month_avg']), 1) : 0,
            'current_year_avg' => isset($current_year_data['current_year_avg']) ? number_format(floatval($current_year_data['current_year_avg']), 1) : 0,
            'current_year_min' => isset($current_year_data['current_year_min']) ? number_format(floatval($current_year_data['current_year_min']), 1) : 0,
            'current_year_max' => isset($current_year_data['current_year_max']) ? number_format(floatval($current_year_data['current_year_max']), 1) : 0,
            'average_price_difference' => isset($current_month_data['current_month_avg']) ? number_format(floatval($current_year_data['current_year_avg']) - floatval($current_month_data['current_month_avg']), 1) : 0,

            'max_price_difference' => isset($current_month_data['current_month_avg']) ? number_format(floatval($current_year_data['current_year_max']) - floatval($current_month_data['current_month_avg']), 1) : 0,
            'min_price_difference' => isset($current_month_data['current_month_avg']) ? number_format(floatval($current_year_data['current_year_min']) - floatval($current_month_data['current_month_avg']), 1) : 0,
            'average_price_percentage' => isset($current_month_data['current_month_avg']) && floatval($current_month_data['current_month_avg']) != 0
                ? number_format((floatval($current_year_data['current_year_avg']) - floatval($current_month_data['current_month_avg'])) / floatval($current_month_data['current_month_avg']) * 100, 1)
                : 0,
            'max_price_percentage' => isset($current_month_data['current_month_avg']) && floatval($current_month_data['current_month_avg']) != 0
                ? number_format((floatval($current_year_data['current_year_max']) - floatval($current_month_data['current_month_avg'])) / floatval($current_month_data['current_month_avg']) * 100, 1)
                : 0,
            'min_price_percentage' => isset($current_month_data['current_month_avg']) && floatval($current_month_data['current_month_avg']) != 0
                ? number_format((floatval($current_year_data['current_year_min']) - floatval($current_month_data['current_month_avg'])) / floatval($current_month_data['current_month_avg']) * 100, 1)
                : 0,
            'month_price_difference' => isset($month_price_difference) ? number_format(floatval($month_price_difference), 1) : 0,
            'month_price_percentage' => isset($month_price_percentage) ? number_format(floatval($month_price_percentage), 1) : 0
        ];

        return $result;
    }

    public function get_last_three_months_average_prices($end, $commodity, $commodityTwo)
    {
        // Convert the end date to a PHP DateTime object
        $end_date = new DateTime($end);
        // Get the last three months, including the end date month
        $months = [];
        $average_prices_commodity = [];
        $average_prices_commodityTwo = [];
        for ($i = 0; $i < 3; $i++) {
            // Add the month to the array (month only)
            $months[] = $end_date->format('F');

            // Calculate the start date for the current month
            $start_date = clone $end_date;
            $start_date->modify('first day of this month');

            // Query to retrieve the average price for commodity 1 for the current month
            $this->db->select("AVG(`chart_item_cost`) AS avg_price");
            $this->db->from("chart_item");
            $this->db->where("MONTH(chart_date)", $start_date->format('m'));
            $this->db->where("YEAR(chart_date)", $start_date->format('Y'));
            $this->db->where("chart_item_name", $commodity);
            $query_commodity = $this->db->get();
            $result_commodity = $query_commodity->row_array();

            // Query to retrieve the average price for commodity 2 for the current month
            $this->db->select("AVG(`chart_item_cost`) AS avg_price");
            $this->db->from("chart_item");
            $this->db->where("MONTH(chart_date)", $start_date->format('m'));
            $this->db->where("YEAR(chart_date)", $start_date->format('Y'));
            $this->db->where("chart_item_name", $commodityTwo);
            $query_commodityTwo = $this->db->get();
            $result_commodityTwo = $query_commodityTwo->row_array();

            // Add the average prices to the respective arrays
            $average_prices_commodity[] = isset($result_commodity['avg_price']) ? $result_commodity['avg_price'] : 0;
            $average_prices_commodityTwo[] = isset($result_commodityTwo['avg_price']) ? $result_commodityTwo['avg_price'] : 0;

            // Move to the previous month
            $end_date->modify('first day of previous month');
        }

        return [
            'avg_price_commodity' => array_reverse($average_prices_commodity), // Reverse the array to get the correct order
            'avg_price_commodityTwo' => array_reverse($average_prices_commodityTwo), // Reverse the array to get the correct order
            'month' => array_reverse($months) // Reverse the array to get the correct order
        ];
    }

    public function get_last_three_years_average_prices($end, $commodity, $commodityTwo) 
    {
        // Convert the end date to a PHP DateTime object
        $end_date = new DateTime($end);

        // Get the last three years, including the end date year
        $years = [];
        $average_prices_commodity = [];
        $average_prices_commodityTwo = [];
        for ($i = 0; $i < 3; $i++) {
            // Add the year to the array
            $years[] = $end_date->format('Y');

            // Calculate the start date for the current year
            $start_date = clone $end_date;
            $start_date->modify('first day of January');

            // Query to retrieve the average price for commodity 1 for the current year
            $this->db->select("AVG(`chart_item_cost`) AS avg_price");
            $this->db->from("chart_item");
            $this->db->where("YEAR(chart_date)", $start_date->format('Y'));
            $this->db->where("chart_item_name", $commodity);
            $query_commodity = $this->db->get();
            $result_commodity = $query_commodity->row_array();

            // Query to retrieve the average price for commodity 2 for the current year
            $this->db->select("AVG(`chart_item_cost`) AS avg_price");
            $this->db->from("chart_item");
            $this->db->where("YEAR(chart_date)", $start_date->format('Y'));
            $this->db->where("chart_item_name", $commodityTwo);
            $query_commodityTwo = $this->db->get();
            $result_commodityTwo = $query_commodityTwo->row_array();

            // Add the average prices to the respective arrays
            $average_prices_commodity[] = isset($result_commodity['avg_price']) ? $result_commodity['avg_price'] : 0;
            $average_prices_commodityTwo[] = isset($result_commodityTwo['avg_price']) ? $result_commodityTwo['avg_price'] : 0;

            // Move to the previous year
            $end_date->modify('-1 year');
        }

        return [
            'avg_price_commodity' => array_reverse($average_prices_commodity), // Reverse the array to get the correct order
            'avg_price_commodityTwo' => array_reverse($average_prices_commodityTwo), // Reverse the array to get the correct order
            'year' => array_reverse($years) // Reverse the array to get the correct order
        ];
    }

    public function year_price_one($start, $end, $commodity_head,$commodity)
    {

        $head = $this->get_head($commodity_head);
        $query = $this->db->query("
            SELECT 
                MAX(chart_date) AS chart_date,  -- Last date of the year
                YEAR(chart_date) AS year, 
                CAST(AVG(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS chart_item_cost2, 
                CAST(MAX(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS max_cost, 
                CAST(MIN(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS min_cost
            FROM chart_item
            WHERE chart_item_name = ? 
              AND chart_cat_id = ? 
              AND chart_date BETWEEN ? AND ?
            GROUP BY YEAR(chart_date)
            ORDER BY chart_date ASC
        ", [$commodity, $head, $start, $end]);

        return $query->result_array();
    }

    public function year_end_price_one($end, $commodity)
    {
        $query = $this->db->query("
            SELECT
                MAX(chart_date) AS chart_date,  -- Last date of the year
                YEAR(chart_date) AS year, 
                ROUND(AVG(chart_item_cost), 1) AS avg_cost, 
                ROUND(MIN(chart_item_cost), 1) AS min_cost, 
                ROUND(MAX(chart_item_cost), 1) AS max_cost, 
                chart_price_unit
            FROM chart_item 
            WHERE chart_item_name = ? 
                AND chart_date = ?
            GROUP BY YEAR(chart_date)
        ", array($commodity, $end));

        return $query->num_rows() > 0 ? $query->result_array() : [];
    }

    public function year_price_two($start, $end, $commodityTwo)
    {
        $query = $this->db->query("
            SELECT 
                MAX(chart_date) AS chart_date,  -- Last date of the year
                YEAR(chart_date) AS year, 
                ROUND(AVG(chart_item_cost), 1) AS avg_cost, 
                ROUND(MIN(chart_item_cost), 1) AS min_cost, 
                ROUND(MAX(chart_item_cost), 1) AS max_cost, 
                chart_price_unit
            FROM chart_item 
            WHERE chart_item_name = ? 
                AND chart_date BETWEEN ? AND ?
            GROUP BY YEAR(chart_date)
        ", array($commodityTwo, $start, $end));

        return $query->result_array();
    }

    public function get_quarterly_date($start, $end, $commodity)
    {
        $head = $this->get_head($commodity);
        $second_commodity = isset($_POST['commodityTwo']) ? $_POST['commodityTwo'] : '';
        $commodity_query = "";
        if (!empty($second_commodity)) {
            $commodity_query = " OR chart_item_name = '$second_commodity'";
        }
        $query = $this->db->query("
            SELECT *, MAX(chart_date) AS chart_date 
            FROM chart_item 
            WHERE chart_date BETWEEN '$start' AND '$end' 
              AND (chart_item_name = '$commodity' $commodity_query) 
            GROUP BY YEAR(chart_date), QUARTER(chart_date)
        ");
        return $query->result_array();
    }

    public function get_quarterly_start_date($start, $end, $commodity)
    {
        $query = $this->db->query("
            SELECT 
                YEAR(chart_date) AS year,
                QUARTER(chart_date) AS quarter,
                AVG(chart_item_cost) AS chart_item_cost,
                chart_price_unit,
                ROUND(AVG(chart_item_cost), 1) AS avg_cost,
                ROUND(MIN(chart_item_cost), 1) AS min_cost,
                ROUND(MAX(chart_item_cost), 1) AS max_cost
            FROM chart_item 
            WHERE chart_date BETWEEN '$start' AND '$end' 
              AND chart_item_name = '$commodity' 
            GROUP BY YEAR(chart_date), QUARTER(chart_date)
        ");
        return $query->row_array();
    }

    public function get_quarterly_end_date($end, $commodity)
    {
        $query = $this->db->query("
            SELECT 
                YEAR(chart_date) AS year,
                QUARTER(chart_date) AS quarter,
                AVG(chart_item_cost) AS chart_item_cost,
                chart_price_unit,
                ROUND(AVG(chart_item_cost), 1) AS avg_cost,
                ROUND(MIN(chart_item_cost), 1) AS min_cost,
                ROUND(MAX(chart_item_cost), 1) AS max_cost
            FROM chart_item 
            WHERE chart_date <= '$end' 
              AND chart_item_name = '$commodity' 
            GROUP BY YEAR(chart_date), QUARTER(chart_date)
        ");
        return $query->result_array();
    }

    public function get_quarterly_price_one($start, $end, $commodity_head, $commodity)
    {
        // Determine the commodity head
        $head = $this->get_head($commodity_head);

        // SQL query to fetch and aggregate data by quarter
        $query = $this->db->query("
            SELECT 
                chart_id, 
                chart_item_name, 
                MAX(chart_date) AS chart_date,  -- Last date of the year
                chart_cat_id, 
                chart_item_cost, 
                chart_price_unit, 
                chart_exis_duty,
                CAST(AVG(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS chart_item_cost2,
                CAST(MAX(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS max_cost,
                CAST(MIN(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS min_cost
            FROM chart_item 
            WHERE chart_item_name = '$commodity' 
              AND chart_cat_id = '$head' 
              AND chart_date BETWEEN '$start' AND '$end' 
            GROUP BY YEAR(chart_date), QUARTER(chart_date)
        ");

        // Return the results as an array
        return $query->result_array();
    }

    public function get_quarterly_end_price_one($end, $commodity)
    {
        $query = $this->db->query("
            SELECT 
                YEAR(chart_date) AS year,
                QUARTER(chart_date) AS quarter,
                AVG(chart_item_cost) AS chart_item_cost,
                chart_price_unit,
                ROUND(AVG(chart_item_cost), 1) AS chart_item_cost2,
                ROUND(MIN(chart_item_cost), 1) AS min_cost,
                ROUND(MAX(chart_item_cost), 1) AS max_cost
            FROM chart_item 
            WHERE chart_item_name = '$commodity' 
              AND chart_date <= '$end' 
            GROUP BY YEAR(chart_date), QUARTER(chart_date)
        ");
        return $query->result_array();
    }

    function analysis($start, $end, $commodity, $commodityTwo)
    {
        // $check = $_SESSION['weeksd'];
        if ($start != '' && $end != '' && $commodity != '' || $commodityTwo != '') {
            $this->db->where("date(chart_date) >='$start' and date(chart_date) <='$end'");
            $this->db->where('chart_item_name', $commodity);
            $this->db->or_where('chart_item_name', $commodityTwo);
        }
        $this->db->select('*, chart_id, chart_item_name,chart_cat_id, CAST(MAX(chart_item_cost) AS DECIMAL(10,1)) as max_cost, CAST(MIN(chart_item_cost) AS DECIMAL(10,1)) as min_cost, CAST(AVG(chart_item_cost) AS DECIMAL(10,1)) as avg_cost, CAST(chart_item_cost  AS DECIMAL(10, 1)) as item_cost');
        // print_r($query);die;
        $query = $this->db->get('chart_item');
        return $query->result_array();
    }

    function analyses($start, $end, $commodity)
    {
        if ($start != '' && $end != '' && $commodity != '') {
            $this->db->where("date(chart_date) >='$start' and date(chart_date) <='$end'");
            $this->db->where('chart_item_name', $commodity);
            $this->db->where('chart_cat_id', $_SESSION['commodity_head']);
        }
        $this->db->select('*, chart_id, chart_item_name,chart_cat_id, CAST(AVG(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS avg_cost, CAST(MAX(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS max_cost, CAST(MIN(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS min_cost, CAST(chart_item_cost  AS DECIMAL(10, 1)) as item_cost');
        $this->db->group_by('chart_item_name');
        $this->db->order_by('chart_date', 'ASC');
        // echo $this->db->last_query();die;

        $query = $this->db->get('chart_item');
        return $query->result_array();
    }

    function analysis_one($start, $end, $commodity)
    {
        if ($start != '' && $end != '' && $commodity != '') {
            $this->db->where("date(chart_date) >='$start' and date(chart_date) <='$end'");
            $this->db->where('chart_item_name', $commodity);
        }
        $this->db->select('chart_id, chart_date,chart_item_name,chart_cat_id, MAX(chart_item_cost) as max_cost, MIN(chart_item_cost) as min_cost');
        $this->db->from('chart_item');
        $query = $this->db->get();
        return $query->result_array();
    }

    function analysis_two($start, $end, $commodity, $commodityTwo)
    {
        if ($start != '' && $end != '' && $commodity != '' && $commodityTwo != '') {
            $this->db->where("date(chart_date) >='$start' and date(chart_date) <='$end'");
            $this->db->where('chart_item_name', $commodity);
            $this->db->or_where('chart_item_name', $commodityTwo);
        }
        $this->db->select('*');
        $this->db->from('chart_item');
        $query = $this->db->get();
        return $query->result_array();
    }

    function week_min($start, $end, $commodity)
    {
        
        $head = $_SESSION['commodity_head'];
        $query = $this->db->query("SELECT 
        AVG(avg_cost) AS avg_cost,
        MIN(min_cost) AS min_cost,
        MAX(max_cost) AS max_cost
      FROM (
        SELECT 
          WEEK(chart_date) date1, 
          chart_date, 
          chart_item_name, 
          CAST(AVG(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS avg_cost, 
          CAST(MAX(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS max_cost, 
          CAST(MIN(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS min_cost
        FROM chart_item 
        WHERE 
          date(chart_date) >= '$start' 
          AND date(chart_date) <= '$end' 
          AND `chart_item_name` = '$commodity' 
          AND `chart_cat_id` = '$head'
        GROUP BY chart_item_name
        ORDER BY chart_date ASC 
      ) subquery
      ");
        return $query->result_array();
    }

    function month_min($start, $end, $commodity)
    {
       
        $head = $_SESSION['commodity_head'];
        $query = $this->db->query("SELECT 
                            MAX(subq.max_cost) AS max_cost, 
                            MIN(subq.min_cost) AS min_cost, 
                            AVG(subq.avg_cost) AS avg_cost 
                            FROM (
                            SELECT MONTH(chart_date) date1, 
                                chart_date, 
                                chart_item_name, 
                                chart_item_cost, 
                                CAST(AVG(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS avg_cost, 
                                CAST(MAX(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS max_cost, 
                                CAST(MIN(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS min_cost 
                            FROM chart_item 
                            WHERE DATE(chart_date) >= '$start' 
                            AND DATE(chart_date) <= '$end' 
                            AND `chart_item_name` = '$commodity' 
                            AND `chart_cat_id` = '$head'
                            GROUP BY chart_item_name 
                            ORDER BY chart_date ASC
                            ) AS subq;
                        ");
        // echo $this->db->last_query();die;
        $array = $query->result_array();
        return $array;
    }

    function year_min($start, $end, $commodity_head,$commodity)
    {
        $head = $this->get_head($commodity_head);

        $query = $this->db->query("SELECT 
        AVG(avg_cost) AS avg_cost,
        MIN(min_cost) AS min_cost,
        MAX(max_cost) AS max_cost
      FROM (
        SELECT 
          YEAR(chart_date) date1, 
          chart_date, 
          chart_item_name, 
          CAST(AVG(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS avg_cost, 
          CAST(MAX(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS max_cost, 
          CAST(MIN(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS min_cost
        FROM chart_item 
        WHERE 
          date(chart_date) >= '$start' 
          AND date(chart_date) <= '$end' 
          AND `chart_item_name` = '$commodity' 
          AND `chart_cat_id` = '$head'
        GROUP BY chart_item_name
        ORDER BY chart_date ASC 
      ) subquery
      ");
        //   echo $this->db->last_query();die;
        return $query->result_array();
    }

    function get_quarterly_year_min($start, $end, $commodity_head, $commodity)
    {
        // Use session library for session data
        $head = $this->get_head($commodity_head);
        $query = $this->db->query("SELECT 
                AVG(avg_cost) AS avg_cost,
                MIN(min_cost) AS min_cost,
                MAX(max_cost) AS max_cost
              FROM (
                SELECT 
                  QUARTER(chart_date) date1, 
                  chart_date, 
                  chart_item_name, 
                  CAST(AVG(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS avg_cost, 
                  CAST(MAX(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS max_cost, 
                  CAST(MIN(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,1)) AS min_cost
                FROM chart_item 
                WHERE 
                  date(chart_date) >= '$start' 
                  AND date(chart_date) <= '$end' 
                  AND `chart_item_name` = '$commodity' 
                  AND `chart_cat_id` = '$head'
                GROUP BY chart_item_name
                ORDER BY chart_date ASC 
              ) subquery
              ");
        return $query->result_array();
    }

    public function left_uom($start, $end, $commodity_head ,$commodity)
    {
        $head = $this->get_head($commodity_head);
        $query = $this->db->where("date(chart_date) >='$start' and date(chart_date) <='$end'")->where('chart_item_name', $commodity)->where('chart_cat_id', $head)->distinct()->select('chart_price_unit')->get('chart_item');
        $array = $query->result_array();
        return $array;
    }

    public function right_uom($start, $end, $commodityTwo)
    {
        $query = $this->db->where("date(chart_date) >='$start' and date(chart_date) <='$end'")->where('chart_item_name', $commodityTwo)->where('chart_cat_id', $_SESSION['commodity_head'])->distinct()->select('chart_price_unit')->get('chart_item');
        $array = $query->result_array();
        return $array;
    }

    public function editCir($id)
    {
        $this->db->where('id', $id);
        $this->db->select('*');
        $result = $this->db->get('cir_reports');
        $array = $result->result_array();
        return $array;
    }

    public function editForcast($id)
    {
        $this->db->where('id', $id);
        $this->db->select('*');
        $result = $this->db->get('forcast_reports');
        $array = $result->result_array();
        return $array;
    }

    public function editLiteCir($id)
    {
        $this->db->where('id', $id);
        $this->db->select('*');
        $result = $this->db->get('lite_cir_reports');
        $array = $result->result_array();
        return $array;
    }

    public function get_combined_price_data_dynamic($start, $end, $commodity_head, $commodity, $special_commodities)
    {
        // Get the commodity head from session or parameter
        $head = $this->get_head($commodity_head);

        // Define the boundary date for 2024 and next year for comparison
        $boundary_date = '2024-12-31';
        $next_year = '2025-01-01';

        // Check if the current commodity is in the special commodities list
        $is_special_commodity = in_array($commodity, $special_commodities);

        // Initialize an array to hold the query parts
        $query_parts = [];
        $params = [];

        // Case 1: If commodity is special, always use data from static_chart_data
        if ($is_special_commodity) {
            $query_parts[] = "
                SELECT 
                    chart_item_name, 
                    chart_cat_id, 
                    chart_date, 
                    CAST(chart_item_cost AS DECIMAL(10,2)) AS chart_item_cost2, 
                    NULL AS max_cost, 
                    NULL AS min_cost 
                FROM `static_chart_data`
                WHERE chart_item_name = ? 
                  AND chart_cat_id = ? 
                  AND chart_date BETWEEN ? AND ? 
                GROUP BY YEAR(chart_date), MONTH(chart_date)
            ";
            $params = array_merge($params, [$commodity, $head, $start, $end]);
        } else {
            // Case 2: Data only from static table (static_chart_data) for the year 2024
            if ($end < $boundary_date || ($start >= $boundary_date && $end < $next_year)) {
                $query_parts[] = "
                    SELECT 
                        chart_item_name, 
                        chart_cat_id, 
                        chart_date, 
                        CAST(chart_item_cost AS DECIMAL(10,2)) AS chart_item_cost2, 
                        NULL AS max_cost, 
                        NULL AS min_cost 
                    FROM `static_chart_data`
                    WHERE chart_item_name = ? 
                      AND chart_cat_id = ? 
                      AND chart_date BETWEEN ? AND ?
                    GROUP BY YEAR(chart_date), MONTH(chart_date)
                ";
                $params = array_merge($params, [$commodity, $head, $start, $end]);
            }

            // Case 3: Data from static table for 2024, and dynamic table for after 2024
            if ($start < $boundary_date && $end >= $boundary_date) {
                // Static data for before 2025
                $query_parts[] = "
                    SELECT 
                        chart_item_name, 
                        chart_cat_id, 
                        chart_date, 
                        CAST(chart_item_cost AS DECIMAL(10,2)) AS chart_item_cost2, 
                        NULL AS max_cost, 
                        NULL AS min_cost 
                    FROM `static_chart_data`
                    WHERE chart_item_name = ? 
                      AND chart_cat_id = ? 
                      AND chart_date BETWEEN ? AND ?
                    GROUP BY YEAR(chart_date), MONTH(chart_date)
                ";
                $params = array_merge($params, [$commodity, $head, $start, $boundary_date]);

                // Dynamic data for after 2024
                $query_parts[] = "
                    SELECT 
                        chart_item_name, 
                        chart_cat_id, 
                        chart_date,                         
                        CAST(SUM(CAST(chart_item_cost AS FLOAT)) / COUNT(chart_item_cost) AS DECIMAL(10,2)) AS chart_item_cost2, 
                        CAST(MAX(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,2)) AS max_cost, 
                        CAST(MIN(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,2)) AS min_cost 
                    FROM `chart_item`
                    WHERE chart_item_name = ? 
                      AND chart_cat_id = ? 
                      AND chart_date BETWEEN ? AND ?
                    GROUP BY YEAR(chart_date), MONTH(chart_date)
                ";
                $params = array_merge($params, [$commodity, $head, $next_year, $end]);
            }

            // Case 4: Data only from dynamic table (chart_item) for after 2024
            if ($start >= $next_year) {
                $query_parts[] = "
                    SELECT 
                        chart_item_name, 
                        chart_cat_id, 
                        chart_date, 
                        CAST(SUM(CAST(chart_item_cost AS FLOAT)) / COUNT(chart_item_cost) AS DECIMAL(10,2)) AS chart_item_cost2, 
                        CAST(MAX(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,2)) AS max_cost, 
                        CAST(MIN(CAST(chart_item_cost AS FLOAT)) AS DECIMAL(10,2)) AS min_cost 
                    FROM `chart_item`
                    WHERE chart_item_name = ? 
                      AND chart_cat_id = ? 
                      AND chart_date BETWEEN ? AND ?
                    GROUP BY YEAR(chart_date), MONTH(chart_date)
                ";
                $params = array_merge($params, [$commodity, $head, $start, $end]);
            }
        }

        // Combine the query parts using UNION
        $query = implode(" UNION ", $query_parts) . " ORDER BY chart_date";

        // Execute the query
        $result = $this->db->query($query, $params);

        return $result->result_array();
    }
    public function get_combined_year_trend_price_one($start, $end, $commodity_head, $commodity,$special_commodities)
    {

        // Check if the commodity is in the special commodities list
        $is_special_commodity = in_array($commodity, $special_commodities);
        
        // Get the commodity head
        $head = $this->get_head($commodity_head);
        
        // Boundary dates
        $boundary_date = '2024-12-31';
        $next_year = '2025-01-01';

        // Initialize query parts and params
        $query_parts = [];
        $params = [];

        // Case 1: End date is within 2024 (using static_chart_data only)
        if ($end <= $boundary_date || $is_special_commodity) {
            $query_parts[] = "
                WITH MonthlyAvg AS (
                    SELECT DATE_FORMAT(chart_date, '%Y-%m') AS month,
                           SUM(chart_item_cost) / NULLIF(COUNT(chart_item_cost), 0) AS monthly_avg
                    FROM static_chart_data
                    WHERE chart_item_name = ? 
                      AND chart_cat_id = ? 
                      AND chart_date BETWEEN ? AND ?  
                    GROUP BY month
                )
                SELECT ROUND(AVG(monthly_avg), 2) AS yearly_avg,
                       ROUND(MAX(monthly_avg), 2) AS max_avg,
                       ROUND(MIN(monthly_avg), 2) AS min_avg
                FROM MonthlyAvg";
            
            // Add parameters for the query
            array_push($params, $commodity, $head, $start, $end);
        }

        // Case 2: Start date is before 2024 and End date is after 2024 (using both static_chart_data and chart_item)
        if ($start < $boundary_date && $end >= $next_year && !$is_special_commodity) {
            $query_parts[] = "
                WITH MonthlyAvg AS (
                    -- Static data for months before 2024
                    SELECT DATE_FORMAT(chart_date, '%Y-%m') AS month,
                           SUM(chart_item_cost) / NULLIF(COUNT(chart_item_cost), 0) AS monthly_avg
                    FROM static_chart_data
                    WHERE chart_item_name = ? 
                      AND chart_cat_id = ? 
                      AND chart_date BETWEEN ? AND ?  
                    GROUP BY month

                    UNION ALL

                    -- Chart item data for months after 2024
                    SELECT DATE_FORMAT(chart_date, '%Y-%m') AS month,
                           SUM(chart_item_cost) / NULLIF(COUNT(chart_item_cost), 0) AS monthly_avg
                    FROM chart_item
                    WHERE chart_item_name = ? 
                      AND chart_cat_id = ? 
                      AND chart_date BETWEEN ? AND ?  
                    GROUP BY month
                )
                SELECT ROUND(AVG(monthly_avg), 2) AS yearly_avg,
                       ROUND(MAX(monthly_avg), 2) AS max_avg,
                       ROUND(MIN(monthly_avg), 2) AS min_avg
                FROM MonthlyAvg";
            
            // Add parameters for the query
            array_push($params, $commodity, $head, $start, $boundary_date, $commodity, $head, $next_year, $end);
        }

        // Case 3: Start date is after 2024 (using chart_item only)
        if ($start >= $next_year && !$is_special_commodity) {
            $query_parts[] = "
                WITH MonthlyAvg AS (
                    SELECT DATE_FORMAT(chart_date, '%Y-%m') AS month,
                           SUM(chart_item_cost) / NULLIF(COUNT(chart_item_cost), 0) AS monthly_avg
                    FROM chart_item
                    WHERE chart_item_name = ? 
                      AND chart_cat_id = ? 
                      AND chart_date BETWEEN ? AND ?  
                    GROUP BY month
                )
                SELECT ROUND(AVG(monthly_avg), 2) AS yearly_avg,
                       ROUND(MAX(monthly_avg), 2) AS max_avg,
                       ROUND(MIN(monthly_avg), 2) AS min_avg
                FROM MonthlyAvg";
            
            // Add parameters for the query
            array_push($params, $commodity, $head, $start, $end);
        }

        // Combine all query parts
        $query = implode(" UNION ", $query_parts);

        // Log the query for debugging (you can remove this in production)
        log_message('debug', 'Executing query: ' . $query . ' with params: ' . json_encode($params));

        // Execute the query and return the result
        $result = $this->db->query($query, $params);
        
        return $result->row_array();
    }
}