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

class Komisi_sales extends CI_Controller
{
    private $perPage = 10;
    private $title = '';

    public function __construct()
    {
        parent::__construct();
        cek_session_login();
        $this->title = info()['title'];
        $this->load->model('Komisi_sales_model', 'komisi');
        $this->komisi->ensureInfoSetting();
        $this->komisi->ensureMenuEntry();
    }

    public function index()
    {
        if (!$this->komisi->isFeatureEnabled()) {
            redirect('errorakses');
            return;
        }

        $this->komisi->ensureSchema();

        $data['title'] = 'Komisi Desain | ' . $this->title;
        $data['tgl'] = tgl_dari_slash() . ' - ' . tgl_sampai_slash();
        $data['sales_options'] = $this->komisi->getSalesOptions();

        $this->template->load('main/themes', 'komisi_sales/index', $data);
    }

    public function ajaxPaginationData()
    {
        cek_nput_post('GET');
        if (!$this->komisi->isFeatureEnabled()) {
            $this->output
                ->set_status_header(403)
                ->set_output('');
            return;
        }

        $this->komisi->ensureSchema();

        $page = (int) $this->input->post('page');
        $offset = $page > 0 ? $page : 0;

        $limits = (int) $this->input->post('limits');
        $limit = $limits > 0 ? $limits : $this->perPage;

        $tgl = trim((string) $this->input->post('tgl'));
        $salesId = (int) $this->input->post('sales_id');

        $conditions = [];
        if ($salesId > 0) {
            $conditions['search']['sales_id'] = $salesId;
        }
        if ($tgl !== '') {
            $date = date_ranges($tgl);
            $conditions['search']['dari'] = date_replace_slash($date['dari']);
            $conditions['search']['sampai'] = date_replace_slash($date['sampai']);
        }

        $countConditions = $conditions;
        $countConditions['returnType'] = 'count';
        $totalRec = $this->komisi->getRows($countConditions);

        $config['target'] = '#dataKomisiSales';
        $config['base_url'] = base_url('komisi-sales/ajaxPaginationData');
        $config['total_rows'] = $totalRec;
        $config['per_page'] = $limit;
        $config['link_func'] = 'search_KomisiSales';
        $this->ajax_pagination->initialize($config);

        $conditions['start'] = $offset;
        $conditions['limit'] = $limit;

        $data['posts'] = $this->komisi->getRows($conditions);
        $data['total_komisi_page'] = 0;

        if (!empty($data['posts'])) {
            foreach ($data['posts'] as $row) {
                $data['total_komisi_page'] += isset($row['komisi_nominal']) ? (int) $row['komisi_nominal'] : 0;
            }
        }

        $this->load->view('komisi_sales/ajax_data', $data, false);
    }
}
