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

class Company extends MY_Controller {
	
	function __construct()
	{
		parent::__construct();

		$this->modul='company';
		$this->title='COMPANY';
		
		$this->load->model('company_mdl','mdl');
	}
	
	public function index()
	{		
		$data = array(
			'title' 	=> 	'Business Partner',
			'content' 	=> 	'company/company_frm',
			't'			=>	$this->session->userdata('t'),
			'u'			=>	$this->session->userdata('u'),
			'h'			=>	$this->session->userdata('h')
			);		
		$this->load('tpl',$data['content'], $data);
		$this->load->view('company/company_frm_cjs');
		$this->load->view('company/company_frm_mjs');
		
	}
	
	function grid(){
		$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
		$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 100;	
		$key = $_REQUEST["q"];
		$rs = $this->mdl->getPaging($page,$rows,$key);
		
		echo json_encode($rs);
	}
	
	function gridAll(){
		$key = $_REQUEST["q"];
		$rs = $this->mdl->getAll($key);
		
		echo json_encode($rs);
	}
	
	function gridSub(){
		$key = $_REQUEST["q"];
		$rs = $this->mdl->getSub($key);
		
		echo json_encode($rs);
	}
	
	function gridSub2(){
		$key = $_REQUEST["q"];
		$rs = $this->mdl->getSub2($key);
		
		echo json_encode($rs);
	}
	
	function gridRow($key){
		$rs = $this->mdl->getRow($key);
		
		echo json_encode($rs);
	}
	
	function gridBuyerAll(){
		$key = $_REQUEST["q"];
		$rs = $this->mdl->getBuyerAll($key);
		
		echo json_encode($rs);
	}
	
	function gridSupplierAll(){
		$key = $_REQUEST["q"];
		$rs = $this->mdl->getSupplierAll($key);
		
		echo json_encode($rs);
	}
	
	function gridSubkonAll(){
		$key = $_REQUEST["q"];
		$rs = $this->mdl->getSubkonAll($key);
		
		echo json_encode($rs);
	}
	
	function getform($cmd){
		$form_data = $this->input->post();
		$id=$form_data['id'];
		$KdPrshn=$form_data['KdPrshn'];
		$TpPrshn=$form_data['TpPrshn'];
		
		// GET COMPANY COUNT #ir
		$checkCompany = $this->mdl->checkCompany($KdPrshn,$TpPrshn);
		foreach ($checkCompany as $x) {
			$countCompany = $x->KdPrshn;
			break;
		}	
		
		unset($form_data['id']);
		if ($cmd=="add"){	
			if ($countCompany > 0) {
				$bol=false;
				$msg="Perusahaan sudah ada!";		
			} else {
				$success = $this->mdl->add($form_data);	
				if ($success){				
					$bol=true;	
					$msg="Perusahaan berhasil ditambah!";
				} else {
					$bol=false;
					$msg="Tambah data gagal.";		
				}
			}
			echo json_encode(array('success'=>$bol,'msg'=>$msg)); 
		} else {
			$this->edit($form_data,$id);
		}
	}
	
	function cetak()
	{
		ini_set('memory_limit', '-1');
		
		$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
		$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 100;	
		$key = $_REQUEST["q"];
		
		$data = array(
			'title' => 	'Business Partner',
			'rs' 	=> 	$this->mdl->getPaging2($page,$rows,$key),
		);	
		
		$this->load->view('company/print',$data);
		
	}
	
	function excel()
	{
		ini_set('memory_limit', '-1');
		
		$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
		$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 100;	
		$key = $_REQUEST["q"];
		
		$data = array(
			'title' => 	'Business Partner',
			'rs' 	=> 	$this->mdl->getPaging2($page,$rows,$key),
		);
		
		$filename ="Business Partner.xls";
		header('Content-type: application/ms-excel');
		header('Content-Disposition: attachment; filename='.$filename);
		$this->load->view('company/print',$data);
	}
function formExcel() {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_FILES['excelFile2'])) {
            $file = $_FILES['excelFile2']['tmp_name'];
            $this->load->library('excel'); // Load library excelnya
            $excel = PHPExcel_IOFactory::load($file);

            // Check if sheet exists
            $dataSheet = $excel->getSheetByName('Business_Partner');
            
            if (!$dataSheet) {
                echo json_encode(['status' => 'error', 'message' => 'Missing sheet: Sheet1']);
                return;
            }
            
            // Extract data from sheet
            $excelData = $dataSheet->toArray(null, true, true, true);
            
            // Initialize counters
            $success_count = 0;
            $errors = [];
            
            // Start database transaction
            $this->db->trans_start();
            
            try {
                foreach ($excelData as $key => $row) {
                    if ($key === 1) continue; // Skip header row
                    
                    // Validate required fields
                    if (empty($row['B']) || empty($row['C'])) {
                        $errors[] = "Row $key: Kode dan Nama harus diisi";
                        continue;
                    }
                    
                    // Prepare data for insertion
                    $current_date = date('Y-m-d H:i:s');
                    
                    // Ganti operator ?? dengan ternary biasa untuk PHP < 7.0
                    $data = [
                        'KdPrshn' => $row['B'],        // Kode
                        'NmPrshn' => $row['C'],        // Nama
                        'TpPrshn' => isset($row['D']) ? $row['D'] : null, // Tipe (optional)
                        'NpwpPrshn' => isset($row['E']) ? $row['E'] : null, // NPWP (optional)
                        'AlmtPrshn' => isset($row['F']) ? $row['F'] : null, // Alamat (optional)
                        'Negara' => isset($row['G']) ? $row['G'] : null, // Negara (optional)
                        'fax' => isset($row['H']) ? $row['H'] : null, // NPWP kedua (optional)
                        'tlp' => isset($row['I']) ? $row['I'] : null, // Telepon (optional)
                        'Valuta' => isset($row['J']) ? $row['J'] : null // Valuta (optional)

                    ];
                    
                    // Check if record already exists
                    $exists = $this->db->get_where('mst_perusahaan', ['KdPrshn' => $data['KdPrshn']])->row();
                    
                    if ($exists) {
                        // Update existing record
                        $this->db->where('KdPrshn', $data['KdPrshn']);
                        $this->db->update('mst_perusahaan', $data);
                    } else {
                        // Insert new record
                        $this->db->insert('mst_perusahaan', $data);
                    }
                    
                    $success_count++;
                }
                
                // Complete transaction
                $this->db->trans_complete();
                
                if ($this->db->trans_status() === FALSE) {
                    throw new Exception('Database transaction failed');
                }

                
					$bol=true;
					$msg="Perusahaan berhasil ditambah!";
                
                
            } catch (Exception $e) {
                $this->db->trans_rollback();
                
					$bol=false;
					$msg="Tambah data gagal.";
                
            }
            
			echo json_encode(array('success'=>$bol,'msg'=>$msg)); 
        } else {
            echo json_encode(['status' => 'error', 'message' => 'No file uploaded']);
        }
    }
}
}