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

class Asset extends CI_Controller {

    public function __construct(){
        parent::__construct();
        $this->load->database();
    }

    public function index(){
        $data = ["active_menu" => "asset"];
        $this->load->view('partials/header', $data);
        $this->load->view('asset/layout');
        $this->load->view('partials/footer');
    }

    // ================= GET DATA =================
    public function get_data(){
        $data = $this->db
            ->select('assets.*, lokasi_asset.nama as nama_lokasi')
            ->from('assets')
            ->join('lokasi_asset', 'lokasi_asset.id = assets.lokasi_asset_id', 'left')
            ->order_by('assets.id','DESC')
            ->get()
            ->result();

        $no = 1;
        $result = [];

        foreach($data as $d){
            $result[] = [
                $no++,
                $d->tanggal_perolehan,
                $d->kode_asset ?? '-',
                $d->nama_asset,
                $d->nama_lokasi ?? '-',
                number_format($d->nilai_perolehan),
                $d->masa_manfaat . ' bln',
                number_format($d->penyusutan_per_bulan),
                $d->created_at,
                '
                <button class="btn btn-sm btn-info btn-detail mb-1 ml-1" data-id="'.$d->id.'"><i class="bi bi-eye"></i></button>
                <button class="btn btn-sm btn-warning btn-edit mb-1 ml-1" data-id="'.$d->id.'">Edit</button>
                <button class="btn btn-sm btn-danger btn-delete mb-1 ml-1" data-id="'.$d->id.'">Hapus</button>
                '
            ];
        }

        echo json_encode(['data'=>$result]);
    }

    // ================= DETAIL ASSET + HISTORY =================
    public function detail($id)
    {
        $data = $this->db
            ->select('a.*, la.nama AS nama_lokasi') // ambil field tambahan dari lokasi_asset
            ->from('assets a')
            ->join('lokasi_asset la', 'a.lokasi_asset_id = la.id', 'left')
            ->where('a.id', $id)
            ->get()
            ->row();
    
        echo json_encode($data);
    }

    public function get_history($asset_id){
        $data = $this->db
            ->where('asset_id', $asset_id)
            ->order_by('created_at', 'DESC')
            ->get('asset_mutations')
            ->result();

        echo json_encode($data);
    }

    // ================= SAVE MANUAL (1 UNIT) =================
    public function save(){
        $harga = preg_replace('/\D/','',$this->input->post('harga'));
        $residu = preg_replace('/\D/','',$this->input->post('residu'));
        $masa = (int)$this->input->post('masa');
        $account_debit_id = (int)$this->input->post('account_asset');
        $account_kredit_id = (int)$this->input->post('account_kas');
        $lokasi_asset_id = (int)$this->input->post('lokasi_asset');
        $tanggal = $this->input->post('tanggal');
        $nama_asset = $this->input->post('nama_asset');
        $keterangan = $this->input->post('keterangan');

        $nilai_perolehan = $harga * 1;
        $penyusutan = ($harga - $residu) / ($masa ?: 1);

        $this->db->trans_start();

        $data = [
            'kode_asset' => 'AST-'.time(),
            'nama_asset' => $nama_asset,
            'harga_per_unit' => $harga,
            'nilai_perolehan' => $nilai_perolehan,
            'tanggal_perolehan' => $tanggal,
            'masa_manfaat' => $masa,
            'nilai_residu' => $residu,
            'penyusutan_per_bulan' => $penyusutan,
            'nilai_buku' => $nilai_perolehan,
            'sumber' => 'manual',
            'account_debit_id' => $account_debit_id,
            'account_kredit_id' => $account_kredit_id,
            'lokasi_asset_id' => $lokasi_asset_id,
            'keterangan' => $keterangan
        ];

        $this->db->insert('assets',$data);
        $asset_id = $this->db->insert_id();
        
        // Journal
        $this->db->insert('journals',[
            'tanggal' => $tanggal,
            'no_ref' => 'AST-'.date('YmdHis').'-'.$asset_id,
            'keterangan' => 'Penambahan Aset '.$nama_asset,
            'ref_type' => 'assets',
            'ref_id' => $asset_id,
            'created_by' => $this->session->userdata('user_id')
        ]);

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

        $this->db->insert('journal_details',[
            'journal_id' => $jid,
            'account_id' => $account_debit_id,
            'debit' => $nilai_perolehan,
            'kredit' => 0
        ]);

        $this->db->insert('journal_details',[
            'journal_id' => $jid,
            'account_id' => $account_kredit_id,
            'debit' => 0,
            'kredit' => $nilai_perolehan
        ]);

        // MUTATION PEROLEHAN
        $this->db->insert('asset_mutations',[
            'asset_id' => $asset_id,
            'tipe' => 'perolehan',
            'nilai' => $nilai_perolehan,
            'keterangan' => 'Perolehan manual: '.$keterangan
        ]);

        $this->db->trans_complete();
        echo json_encode(['status'=>true]);
    }

    // ================= SAVE FROM STOCK =================
    public function save_from_stock(){
        $item_id = $this->input->post('item_id');
        $account_debit_id = (int)$this->input->post('account_asset');
        $lokasi_asset_id = (int)$this->input->post('s_lokasi_asset');
        $masa = (int)$this->input->post('s_masa');
        $residu = preg_replace('/\D/','',$this->input->post('s_residu'));
        $tanggal = $this->input->post('s_tanggal');

        $item = $this->db->get_where('items',['id'=>$item_id])->row();

        if(!$item){
            echo json_encode(['status'=>false,'message'=>'Item tidak ditemukan']);
            return;
        }

        if($item->stok < 1){
            echo json_encode(['status'=>false,'message'=>'Stok tidak cukup']);
            return;
        }

        $harga = $item->harga_beli;
        $nama_asset = $item->nama_barang;
        $nilai_perolehan = $harga;
        $penyusutan = ($harga - $residu) / ($masa ?: 1);

        $this->db->trans_start();

        // INSERT ASSET
        $this->db->insert('assets',[
            'item_id' => $item_id,
            'kode_asset' => 'AST-'.time(),
            'nama_asset' => $nama_asset,
            'harga_per_unit' => $harga,
            'nilai_perolehan' => $nilai_perolehan,
            'tanggal_perolehan' => $tanggal,
            'masa_manfaat' => $masa,
            'nilai_residu' => $residu,
            'penyusutan_per_bulan' => $penyusutan,
            'nilai_buku' => $nilai_perolehan,
            'sumber' => 'gudang',
            'account_debit_id' => $account_debit_id,
            'account_kredit_id' => 21, // Persediaan
            'lokasi_asset_id' => $lokasi_asset_id
        ]);

        $asset_id = $this->db->insert_id();
        
        // Journal
        $this->db->insert('journals',[
            'tanggal' => $tanggal,
            'no_ref' => 'AST-'.date('YmdHis').'-'.$asset_id,
            'keterangan' => 'Penambahan Aset dari Gudang '.$nama_asset,
            'ref_type' => 'assets',
            'ref_id' => $asset_id,
            'created_by' => $this->session->userdata('user_id')
        ]);

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

        // Debit Asset
        $this->db->insert('journal_details',[
            'journal_id' => $jid,
            'account_id' => $account_debit_id,
            'debit' => $nilai_perolehan,
            'kredit' => 0
        ]);

        // Kredit Persediaan
        $this->db->insert('journal_details',[
            'journal_id' => $jid,
            'account_id' => 21,
            'debit' => 0,
            'kredit' => $nilai_perolehan
        ]);

        // UPDATE STOK ITEM (kurangi 1)
        $this->db->where('id', $item_id)
                 ->set('stok', 'stok-1', FALSE)
                 ->update('items');

        // MUTATION DARI GUDANG
        $this->db->insert('asset_mutations',[
            'asset_id' => $asset_id,
            'tipe' => 'perolehan',
            'nilai' => $nilai_perolehan,
            'keterangan' => 'Perolehan dari gudang: '.$nama_asset
        ]);

        $this->db->trans_complete();

        echo json_encode(['status'=>true]);
    }

    // ================= UPDATE =================
    public function update(){
        $id = $this->input->post('id');
        $nama_asset = $this->input->post('nama_asset');
        $lokasi_asset_id = (int)$this->input->post('lokasi_asset');
        $keterangan = $this->input->post('keterangan');

        $this->db->trans_start();

        $data = [
            'nama_asset' => $nama_asset,
            'lokasi_asset_id' => $lokasi_asset_id,
            'keterangan' => $keterangan
        ];

        $this->db->where('id',$id);
        $this->db->update('assets',$data);

        // MUTATION EDIT
        $this->db->insert('asset_mutations',[
            'asset_id' => $id,
            'tipe' => 'penambahan',
            'nilai' => 0,
            'keterangan' => 'Edit asset: '.$nama_asset
        ]);

        $this->db->trans_complete();
        echo json_encode(['status'=>true]);
    }

    // ================= DELETE =================
    public function delete(){
        $id = $this->input->post('id');
        $alasan = $this->input->post('alasan');
        $keterangan = $this->input->post('keterangan');

        $asset = $this->db->get_where('assets',['id'=>$id])->row();

        $this->db->trans_start();

        // Hapus journal
        $journals = $this->db->get_where('journals', ['ref_type'=>'assets', 'ref_id'=>$id])->result();
        foreach($journals as $j){
            $this->db->delete('journal_details', ['journal_id'=>$j->id]);
            $this->db->delete('journals', ['id'=>$j->id]);
        }

        // Hapus asset
        $this->db->delete('assets',['id'=>$id]);

        // MUTATION DELETE
        $this->db->insert('asset_mutations',[
            'asset_id' => $id,
            'tipe' => 'pengurangan',
            'nilai' => $asset->nilai_buku,
            'keterangan' => 'Penghapusan ('.$alasan.'): '.$keterangan
        ]);

        $this->db->trans_complete();
        echo json_encode(['status'=>true]);
    }

    // ================= GET DATA SELECT =================
    public function get_accounts_kas(){
        $data = $this->db
            ->where_in('sub_tipe', ['kas', 'hutang'])
            ->order_by('kode_akun', 'ASC')
            ->get('accounts')
            ->result();
        echo json_encode($data);
    }
    
    public function get_accounts_asset(){
        $data = $this->db
            ->group_start()
            ->like('nama_akun', 'Aset', 'after')
            ->group_end()
            ->order_by('kode_akun', 'ASC')
            ->get('accounts')
            ->result();
        echo json_encode($data);
    }

    public function get_items(){
        $data = $this->db
            ->where('stok > 0')
            ->get('items')
            ->result();
        echo json_encode($data);
    }
    
    public function get_lokasi_asset(){
        $data = $this->db
            ->get('lokasi_asset')
            ->result();
        echo json_encode($data);
    }
}