<?php

defined('BASEPATH') or exit('No direct script access allowed');

class Model_dropshiper extends CI_Model
{
    protected $table = 'dropshiper';
    private $menuParentId = 166;

    public function __construct()
    {
        parent::__construct();
        $this->load->dbforge();
    }

    public function ensureInfoSetting()
    {
        if (!$this->db->table_exists('info')) {
            return;
        }

        if (!$this->db->field_exists('dropshipper_aktif', 'info')) {
            $this->dbforge->add_column('info', [
                'dropshipper_aktif' => [
                    'type' => 'INT',
                    'constraint' => 1,
                    'null' => false,
                    'default' => 1,
                ],
            ]);
        }
    }

    public function isFeatureEnabled()
    {
        if (!$this->db->table_exists('info')) {
            return true;
        }

        $this->ensureInfoSetting();

        $row = $this->db
            ->select('dropshipper_aktif')
            ->from('info')
            ->where('id', 1)
            ->limit(1)
            ->get()
            ->row_array();

        if (!$row || !array_key_exists('dropshipper_aktif', $row)) {
            return true;
        }

        return (int) $row['dropshipper_aktif'] === 1;
    }

    public function setFeatureEnabled($enabled)
    {
        $enabled = (int) $enabled === 1 ? 1 : 0;
        $this->ensureInfoSetting();

        if ($this->db->table_exists('info') && $this->db->field_exists('dropshipper_aktif', 'info')) {
            $this->db
                ->where('id', 1)
                ->update('info', ['dropshipper_aktif' => $enabled]);
        }

        $this->syncMenuVisibility($enabled === 1);
    }

    public function syncMenuVisibility($enabled)
    {
        return $this->ensureMenuEntry($enabled === true || (int) $enabled === 1);
    }

    public function ensureMenuEntry($active = null)
    {
        if (!$this->db->table_exists('menuadmin')) {
            return 0;
        }

        if ($active === null) {
            $active = $this->isFeatureEnabled();
        }
        $activeFlag = $active ? 'Y' : 'N';

        $menu = $this->db
            ->select('idmenu, aktif')
            ->from('menuadmin')
            ->where('link', 'dropshiper')
            ->limit(1)
            ->get()
            ->row_array();

        if (!empty($menu['idmenu'])) {
            if (!isset($menu['aktif']) || $menu['aktif'] !== $activeFlag) {
                $this->db
                    ->where('idmenu', (int) $menu['idmenu'])
                    ->update('menuadmin', ['aktif' => $activeFlag]);
                $this->syncMenuUsersByLevels('1,2,3,4');
            }

            return (int) $menu['idmenu'];
        }

        $parent = $this->db
            ->select('idmenu')
            ->from('menuadmin')
            ->where('idmenu', $this->menuParentId)
            ->limit(1)
            ->get()
            ->row_array();

        if (empty($parent['idmenu'])) {
            $parent = $this->db
                ->select('idmenu')
                ->from('menuadmin')
                ->where('idparent', 0)
                ->where('nama_menu', 'Pelanggan')
                ->limit(1)
                ->get()
                ->row_array();
        }

        if (empty($parent['idmenu'])) {
            return 0;
        }

        $nextOrderRow = $this->db
            ->select_max('urutan')
            ->where('idparent', (int) $parent['idmenu'])
            ->get('menuadmin')
            ->row_array();

        $nextOrder = isset($nextOrderRow['urutan']) ? ((int) $nextOrderRow['urutan'] + 1) : 1;

        $this->db->insert('menuadmin', [
            'idparent' => (int) $parent['idmenu'],
            'id_level' => '1,2,3,4',
            'nama_menu' => 'Dropshipper',
            'link' => 'dropshiper',
            'target' => '_self',
            'link_on' => 'N',
            'treeview' => '',
            'classes' => '',
            'classicon' => 'Y',
            'icon' => '',
            'aktif' => $activeFlag,
            'level' => 'admin',
            'urutan' => $nextOrder,
        ]);

        $menuId = (int) $this->db->insert_id();
        if ($menuId > 0) {
            $this->syncMenuUsersByLevels('1,2,3,4');
        }

        return $menuId;
    }

    /**
     * getData.
     *
     * @return void
     */
    public function getData($params = [])
    {
        $this->db->select('*');
        $this->db->from($this->table);

        if (array_key_exists('where', $params)) {
            foreach ($params['where'] as $key => $val) {
                $this->db->where($key, $val);
            }
        }

        if (array_key_exists('search', $params)) {
            if (!empty($params['search']['keywords'])) {
                $this->db->like('nama_toko', $params['search']['keywords']);
            }
        }

        // Sort data by ascending or desceding order
        if (!empty($params['search']['sortBy'])) {
            $this->db->order_by('id', $params['search']['sortBy']);
        }

        if (array_key_exists('returnType', $params) && $params['returnType'] == 'count') {
            $result = $this->db->count_all_results();
        } else {
            if (array_key_exists('id', $params) || (array_key_exists('returnType', $params) && $params['returnType'] == 'single')) {
                $query = $this->db->get();
                $result = ($query->num_rows() > 0) ? $query->result() : false;
            } else {
                $this->db->order_by('id', 'DESC');
                if (array_key_exists('start', $params) && array_key_exists('limit', $params)) {
                    $this->db->limit($params['limit'], $params['start']);
                } elseif (!array_key_exists('start', $params) && array_key_exists('limit', $params)) {
                    $this->db->limit($params['limit']);
                }

                $query = $this->db->get();
                $result = ($query->num_rows() > 0) ? $query->result() : false;
            }
        }

        // Return fetched data
        return $result;
    }

    /**
     * get_photo.
     *
     * @return void
     */
    public function get_logo($id)
    {
        if ($this->cek_id($id) > 0) {
            $query = $this->db->where('id', $id);
            $query = $this->db->get($this->table);
            $result = $query->row();

            return $result;
        } else {
            return null;
        }
    }

    /**
     * cek_id.
     *
     * @return void
     */
    public function cek_id($id)
    {
        $query = $this->db->select('id');
        $query = $this->db->where('id', $id);
        $query = $this->db->get($this->table);
        $result = $query->num_rows();

        if ($result < 1) {
            $result = 0;
        }

        return $result;
    }

    /**
     * cek_id_dropship.
     *
     * @return void
     */
    public function cek_id_dropship($id)
    {
        $query = $this->db->select('id_dropshiper');
        $query = $this->db->where('id_dropshiper', $id);
        $query = $this->db->get('invoice');
        $result = $query->num_rows();

        if ($result < 1) {
            $result = 0;
        }

        return $result;
    }

    private function syncMenuUsersByLevels($levels)
    {
        if (!$this->db->table_exists('tb_users') || !$this->db->table_exists('hak_akses')) {
            return;
        }
        if (!function_exists('atur_menu')) {
            return;
        }

        $publishedLevels = $this->db
            ->select('id_level')
            ->from('hak_akses')
            ->where('publish', 'Y')
            ->get()
            ->result();

        if (empty($publishedLevels)) {
            return;
        }

        foreach ($publishedLevels as $row) {
            $levelId = isset($row->id_level) ? (int) $row->id_level : 0;
            if ($levelId <= 0) {
                continue;
            }

            $menuIds = atur_menu($levelId);
            $this->db
                ->where('id_level', $levelId)
                ->update('tb_users', ['idmenu' => $menuIds]);
        }
    }
}
