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

class Jurnal 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" => "jurnal"];
        $this->load->view('partials/header', $data);
        $this->load->view('jurnal/layout');
        $this->load->view('partials/footer');
    }

    // =========================
    // GET DATA DATATABLE (SUDAH ADA TOTAL)
    // =========================
    public function get_data()
    {
        $draw   = $_POST['draw'];
        $start  = $_POST['start'];
        $length = $_POST['length'];
        $search = $_POST['search']['value'];

        // ================= TOTAL ALL
        $totalAll = $this->db->count_all('journals');

        // ================= QUERY FILTERED (HITUNG)
        $this->db->from('journals');

        if(!empty($search)){
            $this->db->group_start();
            $this->db->like('no_ref', $search);
            $this->db->or_like('keterangan', $search);
            $this->db->or_like('tanggal', $search);
            $this->db->group_end();
        }

        $filtered = $this->db->count_all_results();

        // ================= QUERY DATA (AMBIL DATA)
        $this->db->select('
            journals.id,
            journals.tanggal,
            journals.no_ref,
            journals.keterangan,
            COALESCE(SUM(journal_details.debit),0) as total_debit,
            COALESCE(SUM(journal_details.kredit),0) as total_kredit
        ');
        $this->db->from('journals');
        $this->db->join('journal_details','journal_details.journal_id = journals.id','LEFT');

        if(!empty($search)){
            $this->db->group_start();
            $this->db->like('journals.no_ref', $search);
            $this->db->or_like('journals.keterangan', $search);
            $this->db->or_like('journals.tanggal', $search);
            $this->db->group_end();
        }

        $this->db->group_by('journals.id');
        $this->db->order_by('journals.tanggal','DESC');
        $this->db->order_by('journals.created_at','DESC');
        $this->db->limit($length, $start);

        $query = $this->db->get()->result();

        // ================= FORMAT
        $data = [];
        $no = $start;

        foreach ($query as $row) {
            $no++;
            
            if($this->session->userdata('role') != 'Admin'){
                
                $aksi = '
                    <button class="btn btn-sm btn-info btn-detail" data-id="'.$row->id.'">Detail</button>
                ';
                
            }
            else {
                $aksi = '
                    <button class="btn btn-sm btn-info btn-detail" data-id="'.$row->id.'">Detail</button>
                    <button class="btn btn-sm btn-danger btn-delete" data-id="'.$row->id.'">Delete</button>
                ';
            }

            $data[] = [
                $no,
                $row->tanggal,
                $row->no_ref,
                $row->keterangan,
                number_format($row->total_debit,0,',','.'),
                number_format($row->total_kredit,0,',','.'),
                $aksi
            ];
        }

        echo json_encode([
            "draw" => $draw,
            "recordsTotal" => $totalAll,
            "recordsFiltered" => $filtered,
            "data" => $data
        ]);
    }

    // =========================
    // GET ACCOUNTS
    // =========================
    public function get_accounts()
    {
        $data = $this->db->order_by('kode_akun','ASC')->get('accounts')->result();
        echo json_encode($data);
    }

    // =========================
    // SAVE
    // =========================
    public function save()
    {
        $tanggal    = $this->input->post('tanggal');
        $no_ref     = 'JR-' . date('YmdHis');
        $keterangan = $this->input->post('keterangan');

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

        if (array_sum($debit) != array_sum($kredit)) {
            echo json_encode([
                'status'=>false,
                'message'=>'Debit & Kredit tidak balance!'
            ]);
            return;
        }

        $this->db->trans_start();

        $this->db->insert('journals', [
            'tanggal' => $tanggal,
            'no_ref' => $no_ref,
            'keterangan' => $keterangan,
            'created_by' => $this->session->userdata('user_id')
        ]);

        $journal_id = $this->db->insert_id();

        for ($i=0; $i<count($accounts); $i++) {
            if ($accounts[$i] == '') continue;

            $this->db->insert('journal_details', [
                'journal_id' => $journal_id,
                'account_id' => $accounts[$i],
                'debit' => $debit[$i] ?: 0,
                'kredit' => $kredit[$i] ?: 0
            ]);
        }

        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {

            echo json_encode([
                'status'=>false,
                'message'=>'Gagal simpan jurnal'
            ]);
            return;

        }

        // ================= LOG ACTIVITY =================
        log_activity(
            'Jurnal',
            'create',
            'Membuat jurnal No Ref: '.$no_ref,
            'success'
        );

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

    // =========================
    // DETAIL
    // =========================
    public function detail($id)
    {
        $header = $this->db->get_where('journals',['id'=>$id])->row();

        $detail = $this->db
            ->select('accounts.kode_akun, accounts.nama_akun, journal_details.*')
            ->from('journal_details')
            ->join('accounts','accounts.id = journal_details.account_id')
            ->where('journal_id',$id)
            ->get()->result();
        
        // print_r($header);
        
        $userid = $header->created_by;
        $user = $this->db
            ->select('nama')
            ->where('id', $userid)
            ->get('users')
            ->row();

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

    // =========================
    // DELETE
    // =========================
    public function delete($id)
    {
        $journal = $this->db->get_where('journals', ['id' => $id])->row();
    
        // VALIDASI
        if (!$journal) {
            echo json_encode([
                'status' => false,
                'message' => 'Jurnal tidak ditemukan'
            ]);
            return;
        }
    
        $this->db->trans_start();
        
        // =========================
        // HANDLE STOCK LOGS
        // =========================
        if ($journal->ref_type == 'stock_logs') {
    
            $stock = $this->db
                ->select('item_id, warehouse_id')
                ->where('id', $journal->ref_id)
                ->get('stock_logs')
                ->row();
    
            if ($stock) {
    
                // hapus log stok
                $this->db->delete('stock_logs', ['id' => $journal->ref_id]);
    
                // update stok ulang (pakai item_id saja biar gak ganggu sistem lama)
                $this->update_item_stok($stock->item_id);
            }
        }
    
        // =========================
        // DELETE JOURNAL
        // =========================
        $this->db->delete('journal_details', ['journal_id' => $id]);
        $this->db->delete('journals', ['id' => $id]);
    
        $this->db->trans_complete();
    
        // =========================
        // VALIDASI TRANSAKSI
        // =========================
        if (!$this->db->trans_status()) {
    
            echo json_encode([
                'status' => false,
                'message' => 'Gagal hapus jurnal'
            ]);
            return;
        }
    
        // ================= LOG ACTIVITY =================
        log_activity(
            'Jurnal',
            'delete',
            'Menghapus jurnal no_ref: ' . $journal->no_ref . ' ket: ' . $journal->keterangan,
            'success'
        );
    
        echo json_encode([
            'status' => true, // ✅ FIX
            'message' => 'Jurnal berhasil dihapus',
            'journal' => $journal->ref_type
        ]);
    }

    public function get_base_jurnal()
    {
        echo json_encode(
            $this->db->order_by('kode','ASC')->get('base_journal')->result()
        );
    }

    public function get_base_jurnal_detail($id)
    {
        echo json_encode(
            $this->db->where('base_journal_id',$id)
                     ->get('base_journal_detail')
                     ->result()
        );
    }
    
    private function update_item_stok($item_id)
    {
        $stok = $this->db->query("
            SELECT COALESCE(SUM(qty * IF(tipe='masuk',1,-1)),0) as stok
            FROM stock_logs
            WHERE item_id = ?
        ", [$item_id])->row()->stok;

        $this->db->where('id', $item_id)
                 ->update('items', [
                     'stok' => $stok
                 ]);
    }
}