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

class Basejurnal extends CI_Controller {

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

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

    // ================= INDEX
    public function index()
    {

        if($this->session->userdata('role') != 'Admin'){
            show_error('Akses ditolak', 403);
        }
        
        $data = [
            "active_menu" => "basejurnal"
        ];

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

    // ================= DATATABLE
    public function get_data()
    {
        $this->dm->setTable('base_journal')
            ->setColumn(
                [null,'kode','nama','deskripsi','is_active',null],
                ['kode','nama'],
                ['id'=>'DESC']
            );

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

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

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

            $status = $row->is_active ? 'Aktif' : 'Nonaktif';

            $data[] = [
                $no,
                $row->kode,
                $row->nama,
                $row->deskripsi,
                $status,
                '
                <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.'">Hapus</button>
                '
            ];
        }

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

public function save()
{
    $this->db->trans_start();

    $kode = trim($this->input->post('kode'));
    $nama = trim($this->input->post('nama'));

    if(empty($kode) || empty($nama)){
        echo json_encode([
            'status' => false,
            'message' => 'Kode & Nama wajib diisi'
        ]);
        return;
    }

    $header = [
        'kode' => $kode,
        'nama' => $nama,
        'deskripsi' => $this->input->post('deskripsi'),
        'is_active' => 1
    ];

    $this->dm->setTable('base_journal')->insert($header);
    $base_id = $this->db->insert_id();

    $accounts = $this->input->post('account_id');
    $posisi   = $this->input->post('posisi');

    if(!empty($accounts)){
        $detail = [];

        foreach ($accounts as $i => $acc) {
            if(empty($acc)) continue;

            $detail[] = [
                'base_journal_id' => $base_id,
                'account_id' => $acc,
                'posisi' => $posisi[$i] ?? 'debit',
                'urutan' => $i + 1
            ];
        }

        if(!empty($detail)){
            $this->db->insert_batch('base_journal_detail', $detail);
        }
    }

    $this->db->trans_complete();

    if (!$this->db->trans_status()) {
        echo json_encode([
            'status' => false,
            'message' => 'Gagal simpan data'
        ]);
        return;
    }

    log_activity(
        'base_journal',
        'create',
        'Membuat base journal kode: '.$kode,
        'success'
    );

    echo json_encode([
        'status' => true,
        'message' => 'Data berhasil disimpan'
    ]);
}

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

    if(empty($id)){
        echo json_encode([
            'status' => false,
            'message' => 'ID tidak valid'
        ]);
        return;
    }

    $this->db->trans_start();

    $header = [
        'kode' => trim($this->input->post('kode')),
        'nama' => trim($this->input->post('nama')),
        'deskripsi' => $this->input->post('deskripsi'),
    ];

    $this->dm->setTable('base_journal')->update($id, $header);

    // 🔥 DELETE OLD DETAIL
    $this->db->where('base_journal_id', $id)->delete('base_journal_detail');

    // 🔥 INSERT NEW DETAIL
    $accounts = $this->input->post('account_id');
    $posisi   = $this->input->post('posisi');

    if(!empty($accounts)){
        $detail = [];

        foreach ($accounts as $i => $acc) {
            if(empty($acc)) continue;

            $detail[] = [
                'base_journal_id' => $id,
                'account_id' => $acc,
                'posisi' => $posisi[$i] ?? 'debit',
                'urutan' => $i + 1
            ];
        }

        if(!empty($detail)){
            $this->db->insert_batch('base_journal_detail', $detail);
        }
    }

    $this->db->trans_complete();

    if (!$this->db->trans_status()) {
        echo json_encode([
            'status' => false,
            'message' => 'Gagal update data'
        ]);
        return;
    }

    log_activity(
        'base_journal',
        'update',
        'Mengubah base journal ID: '.$id.' (kode: '.$header['kode'].')',
        'success'
    );

    echo json_encode([
        'status' => true,
        'message' => 'Data berhasil diupdate'
    ]);
}

    // ================= DETAIL
    public function detail($id)
    {
        $header = $this->dm->setTable('base_journal')->find($id);

        $detail = $this->db
            ->select('d.*, a.nama_akun as account_name')
            ->from('base_journal_detail d')
            ->join('accounts a','a.id = d.account_id','left') // <-- GANTI DI SINI
            ->where('d.base_journal_id',$id)
            ->order_by('d.urutan','ASC')
            ->get()
            ->result();

        echo json_encode([
            'header' => $header,
            'detail' => $detail
        ]);
    }

    public function delete($id = null)
    {
        // set response JSON
        $this->output->set_content_type('application/json');

        if (empty($id)) {
            echo json_encode([
                'status' => false,
                'message' => 'ID tidak valid'
            ]);
            return;
        }

        $this->db->trans_start();

        // hapus detail dulu
        $this->db->where('base_journal_id', $id)->delete('base_journal_detail');

        // hapus header
        $delete = $this->dm->setTable('base_journal')->delete($id);

        $this->db->trans_complete();

        if (!$this->db->trans_status() || !$delete) {
            echo json_encode([
                'status' => false,
                'message' => 'Gagal hapus data'
            ]);
            return;
        }

        // ================= LOG ACTIVITY =================
        log_activity(
            'base_journal',
            'delete',
            'Menghapus base journal ID: '.$id,
            'success'
        );

        echo json_encode([
            'status' => true,
            'message' => 'Data berhasil dihapus'
        ]);
    }

    public function get_list_account()
    {
        $data = $this->db->select('id, nama_akun, kode_akun')
                         ->from('accounts') // sesuaikan tabel kamu
                         ->order_by('kode_akun','ASC')
                         ->get()
                         ->result();

        echo json_encode($data);
    }
}