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

class Komisi_penjualan_model extends CI_Model
{
    private $menuParentId = 155;

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

    public function ensureSchema()
    {
        if ($this->db->table_exists('info') && !$this->db->field_exists('komisi_penjualan_aktif', 'info')) {
            $this->dbforge->add_column('info', ['komisi_penjualan_aktif' => ['type'=>'INT','constraint'=>1,'null'=>false,'default'=>0]]);
        }
        if ($this->db->table_exists('tb_users')) {
            $fields = [];
            if (!$this->db->field_exists('komisi_penjualan_aktif', 'tb_users')) {
                $fields['komisi_penjualan_aktif'] = ['type'=>'INT','constraint'=>1,'null'=>false,'default'=>0];
            }
            if ($fields) $this->dbforge->add_column('tb_users', $fields);
        }
        if ($this->db->table_exists('bahan')) {
            $fields = [];
            if (!$this->db->field_exists('komisi_penjualan_aktif', 'bahan')) {
                $fields['komisi_penjualan_aktif'] = ['type'=>'INT','constraint'=>1,'null'=>false,'default'=>0];
            }
            if (!$this->db->field_exists('komisi_penjualan_tipe', 'bahan')) {
                $fields['komisi_penjualan_tipe'] = ['type'=>'VARCHAR','constraint'=>10,'null'=>false,'default'=>'persen'];
            }
            if (!$this->db->field_exists('komisi_penjualan_nilai', 'bahan')) {
                $fields['komisi_penjualan_nilai'] = ['type'=>'DECIMAL','constraint'=>'15,2','null'=>false,'default'=>'0.00'];
            }
            if ($fields) $this->dbforge->add_column('bahan', $fields);
        }
        if ($this->db->table_exists('invoice')) {
            $fields = [];
            if (!$this->db->field_exists('id_sales_penjualan', 'invoice')) {
                $fields['id_sales_penjualan'] = ['type'=>'INT','constraint'=>11,'null'=>false,'default'=>0];
            }
            if (!$this->db->field_exists('komisi_penjualan_nominal', 'invoice')) {
                $fields['komisi_penjualan_nominal'] = ['type'=>'DECIMAL','constraint'=>'15,2','null'=>false,'default'=>'0.00'];
            }
            if ($fields) $this->dbforge->add_column('invoice', $fields);
        }
    }

    public function isFeatureEnabled()
    {
        $this->ensureSchema();
        if (!$this->db->table_exists('info')) return false;
        $row = $this->db->select('komisi_penjualan_aktif')->where('id',1)->get('info')->row_array();
        return $row && (int)$row['komisi_penjualan_aktif'] === 1;
    }

    public function getSalesOptions()
    {
        $this->ensureSchema();
        return $this->db->select('id_user,nama_lengkap')->from('tb_users')->where('aktif','Y')->where('komisi_penjualan_aktif',1)->order_by('nama_lengkap','ASC')->get()->result_array();
    }

    public function saveInvoiceSales($invoiceId, $salesId)
    {
        $this->ensureSchema();
        $invoiceId=(int)$invoiceId; $salesId=(int)$salesId;
        if ($invoiceId <= 0) return false;
        $valid = $salesId > 0 && $this->db->where('id_user',$salesId)->where('aktif','Y')->where('komisi_penjualan_aktif',1)->count_all_results('tb_users') > 0;
        $this->db->where('id_invoice',$invoiceId)->update('invoice',['id_sales_penjualan'=>$valid?$salesId:0]);
        $this->syncInvoiceAmount($invoiceId);
        return true;
    }

    public function syncInvoiceAmount($invoiceId)
    {
        $this->ensureSchema();
        $invoiceId=(int)$invoiceId;
        $invoice=$this->db->select('id_sales_penjualan')->where('id_invoice',$invoiceId)->get('invoice')->row_array();
        if (!$invoice || (int)$invoice['id_sales_penjualan'] <= 0) $amount=0;
        else {
            $row=$this->db->select("SUM(CASE WHEN b.komisi_penjualan_tipe='nominal' THEN b.komisi_penjualan_nilai*d.jumlah ELSE (((d.harga*d.jumlah)-((d.harga*d.jumlah)*(d.diskon/100)))*b.komisi_penjualan_nilai/100) END) amount",false)
                ->from('invoice_detail d')->join('bahan b','b.id=d.id_bahan','inner')->where('d.id_invoice',$invoiceId)->where('b.komisi_penjualan_aktif',1)->get()->row_array();
            $amount=isset($row['amount'])?(float)$row['amount']:0;
        }
        $this->db->where('id_invoice',$invoiceId)->update('invoice',['komisi_penjualan_nominal'=>round($amount,2)]);
        return $amount;
    }

    public function invoiceRequiresSales($invoiceId)
    {
        $this->ensureSchema();
        return $this->db->from('invoice_detail d')->join('bahan b','b.id=d.id_bahan','inner')->where('d.id_invoice',(int)$invoiceId)->where('b.komisi_penjualan_aktif',1)->where('b.komisi_penjualan_nilai >',0)->count_all_results() > 0;
    }

    public function getRows($params=[])
    {
        $this->ensureSchema();
        $filter=function() use($params){
            $this->db->from('invoice i')->join('tb_users s','s.id_user=i.id_sales_penjualan','inner')->join('tb_users k','k.id_user=i.id_marketing','left')->join('konsumen p','p.id=i.id_konsumen','left');
            $this->db->where('i.status !=','batal')->where('i.id_sales_penjualan >',0)->where('i.komisi_penjualan_nominal >',0);
            if(!empty($params['dari'])) $this->db->where('DATE(i.tgl_trx) >=',$params['dari']);
            if(!empty($params['sampai'])) $this->db->where('DATE(i.tgl_trx) <=',$params['sampai']);
            if(!empty($params['sales_id'])) $this->db->where('i.id_sales_penjualan',(int)$params['sales_id']);
        };
        if(!empty($params['count'])) { $this->db->select('COUNT(*) n',false); $filter(); $r=$this->db->get()->row_array(); return (int)($r['n']??0); }
        $this->db->select("i.id_invoice,i.id_transaksi,i.tgl_trx,i.total_bayar,i.komisi_penjualan_nominal,IFNULL(NULLIF(TRIM(p.nama),''),'Umum') nama_pelanggan,IFNULL(NULLIF(TRIM(s.nama_lengkap),''),'-') nama_sales,IFNULL(NULLIF(TRIM(k.nama_lengkap),''),'-') nama_kasir",false); $filter();
        $this->db->order_by('i.tgl_trx','DESC')->order_by('i.id_invoice','DESC');
        if(isset($params['limit'])) $this->db->limit((int)$params['limit'],(int)($params['start']??0));
        return $this->db->get()->result_array();
    }

    public function ensureMenuEntry($active=null)
    {
        $this->ensureSchema();
        if(!$this->db->table_exists('menuadmin')) return 0;
        if($active===null) $active=$this->isFeatureEnabled();
        $flag=$active?'Y':'N';
        $row=$this->db->where('link','komisi-penjualan')->get('menuadmin')->row_array();
        if($row){ if(($row['nama_menu']??'')!=='Komisi Penjualan'||($row['aktif']??'')!==$flag){ $this->db->where('idmenu',$row['idmenu'])->update('menuadmin',['nama_menu'=>'Komisi Penjualan','aktif'=>$flag]); $this->syncUsers(); $this->clearCache(); } return (int)$row['idmenu']; }
        if(!$this->db->where('idmenu',$this->menuParentId)->count_all_results('menuadmin')) return 0;
        $max=$this->db->select_max('urutan','m')->get('menuadmin')->row_array();
        $this->db->insert('menuadmin',['idparent'=>$this->menuParentId,'id_level'=>'1,2,3,4,5,6','nama_menu'=>'Komisi Penjualan','link'=>'komisi-penjualan','target'=>'_self','link_on'=>'N','treeview'=>'','classes'=>'','classicon'=>'N','icon'=>'','aktif'=>$flag,'level'=>'admin','urutan'=>((int)($max['m']??0)+1)]);
        $this->syncUsers(); $this->clearCache(); return (int)$this->db->insert_id();
    }

    private function syncUsers(){ if(!$this->db->table_exists('tb_users')||!$this->db->table_exists('hak_akses')||!function_exists('atur_menu'))return; foreach($this->db->select('id_level')->where('publish','Y')->get('hak_akses')->result() as $r){ $id=(int)$r->id_level; if($id>0)$this->db->where('id_level',$id)->update('tb_users',['idmenu'=>atur_menu($id)]); } }
    private function clearCache(){ foreach(glob(APPPATH.'cache'.DIRECTORY_SEPARATOR.'sidebar_menu_*')?:[] as $f) if(is_file($f)) @unlink($f); }
}
