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

class Accounts extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('DynamicModel', 'dm');

        if (!$this->session->userdata('logged_in')) {
            redirect('auth');
        }
    }

    public function index()
    {

        if($this->session->userdata('role') != 'Admin'){
            show_error('Akses ditolak', 403);
        }

        $data = [
            "active_menu" => "accounts",
            "parent_accounts" => $this->db->get('accounts')->result()
        ];

        $this->load->view('partials/header', $data);
        $this->load->view('accounts/layout', $data);
        $this->load->view('partials/footer');
    }

    public function get_data()
    {
        $this->dm->setTable('accounts')
            ->setColumn(
                [null,'kode_akun','nama_akun','tipe','posisi','kategori',null],
                ['kode_akun','nama_akun','tipe'],
                ['kode_akun'=>'ASC']
            );

        $list = $this->dm->get_datatables();

        $data = [];
        $no = $_POST['start'];

        foreach ($list as $row) {
            $no++;

            $data[] = [
                $no,
                $row->kode_akun,
                $row->nama_akun,
                ucfirst($row->tipe),
                ucfirst($row->posisi),
                ucfirst($row->kategori),
                '
                <button class="btn btn-sm btn-warning btn-edit" data-id="'.$row->id.'">Edit</button>
                <button class="btn btn-sm btn-danger btn-delete" data-id="'.$row->id.'">Delete</button>
                '
            ];
        }

        echo json_encode([
            "draw" => $_POST['draw'],
            "recordsTotal" => $this->dm->count_all(),
            "recordsFiltered" => $this->dm->count_filtered(),
            "data" => $data
        ]);
    }

    // ================= SAVE
    public function save()
    {
        $tipe = $this->input->post('tipe');

        $data = [
            'kode_akun' => $this->input->post('kode_akun'),
            'nama_akun' => $this->input->post('nama_akun'),
            'tipe'      => $tipe,
            'posisi'    => in_array($tipe, ['asset','expense']) ? 'debit' : 'kredit',
            'kategori'  => in_array($tipe, ['asset','liability','equity']) ? 'neraca' : 'laba_rugi',
            'parent_id' => $this->input->post('parent_id') ?: NULL
        ];

        $insert = $this->dm->setTable('accounts')->insert($data);

        if($insert){
            log_activity(
                'Accounts',
                'create',
                'Menambah akun: '.$data['kode_akun'].' - '.$data['nama_akun']
            );
        }

        echo json_encode([
            'status' => $insert ? true : false,
            'message' => $insert ? 'Data berhasil disimpan' : 'Gagal simpan'
        ]);
    }

    // ================= UPDATE
    public function update()
    {
        $id = $this->input->post('id');
        $tipe = $this->input->post('tipe');

        $data = [
            'kode_akun' => $this->input->post('kode_akun'),
            'nama_akun' => $this->input->post('nama_akun'),
            'tipe'      => $tipe,
            'posisi'    => in_array($tipe, ['asset','expense']) ? 'debit' : 'kredit',
            'kategori'  => in_array($tipe, ['asset','liability','equity']) ? 'neraca' : 'laba_rugi',
            'parent_id' => $this->input->post('parent_id') ?: NULL
        ];

        $update = $this->dm->setTable('accounts')->update($id, $data);

        if($update){
            log_activity(
                'Accounts',
                'update',
                'Update akun ID '.$id.' menjadi: '.$data['kode_akun'].' - '.$data['nama_akun']
            );
        }

        echo json_encode([
            'status' => $update ? true : false,
            'message' => $update ? 'Data berhasil diupdate' : 'Gagal update'
        ]);
    }

    public function detail($id)
    {
        $data = $this->dm->setTable('accounts')->find($id);
        echo json_encode($data);
    }

    public function delete($id)
    {
        // cek apakah jadi parent
        $child = $this->db->where('parent_id',$id)->count_all_results('accounts');

        if($child > 0){
            echo json_encode([
                'status'=>false,
                'message'=>'Tidak bisa hapus, akun punya child'
            ]);
            return;
        }

        $delete = $this->dm->setTable('accounts')->delete($id);

        if($delete){
            log_activity(
                'Accounts',
                'delete',
                'Menghapus akun ID '.$id,
                'success'
            );
        }

        echo json_encode([
            'status' => $delete ? true : false,
            'message' => $delete ? 'Data berhasil dihapus' : 'Gagal hapus'
        ]);
    }
}