<?php

class CategorySettings extends CI_Model
{
    public $recordID;
    public $brCode;
    public $catCode;
    public $orderNo;

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

		$this->load->database();
    }

    public function getCategorysettingsByBrCode($brCode)
    {
        $this->db->order_by('orderNo', 'ASC');
        return $this->db->get_where("categorysettings", array("brCode"=>$brCode));
    }

    public function reassignOrder($brCode)
    {
        $result = $this->getCategorysettingsByBrCode($brCode);

        $i = 1;

        foreach($result->result() as $row)
        {
            $this->db->where(array("brCode"=>$row->brCode, "catCode"=>$row->catCode));
            $this->db->update("categorysettings", array("orderNo"=>$i));

            $i++;
        }
    }

    public function getNextOrderNo($brCode)
    {
        $NextOrderNo = 0;

        $this->db->select("IFNULL(MAX(orderNo), 0) + 1 as NextOrderNo");
        $result = $this->db->get_where("categorysettings", array("brCode"=>$brCode));

        foreach($result->result() as $row)
        $NextOrderNo = $row->NextOrderNo;

        return $NextOrderNo;
    }

    public function addCategorySettings()
    {
        return $this->db->insert('categorysettings', $this);
    }

    public function deleteCategory($brCode, $catCode)
    {
        $result = $this->db->delete('categorysettings', array("brCode"=>$brCode, "catCode"=>$catCode));
        $this->reassignOrder($brCode);
        return $result;
    }
}