<?php

class Package_Model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    public function getCategories($type=null)
    {
        $this->db->select('*');
        $this->db->from('categories');
        if($type != ""){
            $this->db->where('type', $type);
        }
        $this->db->order_by('c_order ASC, category ASC');
        $query = $this->db->get();
        $categories = $query->result();

        return $categories;
    }

    public function getCategoriesWithPackages($province_id, $type=null)
    {
        $this->db->select('*');
        $this->db->from('categories');
        if($type != ""){
            $this->db->where('type', $type);
        }
        $this->db->order_by('c_order ASC, category ASC');
        $query = $this->db->get();
        $categories = $query->result();

        foreach ($categories as &$category) {
            $category->packages = $this->getPackagesByCategory($province_id, $category->id);
        }

        return $categories;
    }

    public function getPackagesByCategory($province_id, $category_id)
    {
        $this->db->where('category_id', $category_id);
        $this->db->where('province_id', $province_id);
        $this->db->order_by('c_order ASC, package_name ASC');
        
        $query = $this->db->get('packages');
        

        // Print the final executed query
        // echo "<pre>Executed Query:\n" . $this->db->last_query() . "</pre>";

        return $query->result();
    }

    public function getPackageDetail($package_id) {
        return $this->db->get_where('packages', ['id' => $package_id])->row();
    }
}