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

class Production_cash_book extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->helper('az_auth');
        az_check_auth('production_cash_book');
        $this->load->helper('az_crud');
        $this->load->library('AZApp');
        $this->crud = $this->azapp->add_crud();
        $this->role_name = $this->session->userdata('role_name');
        $this->iduser = $this->session->userdata('iduser');
        $this->is_admin = ($this->role_name == 'administrator');
        $this->upload_path = APPPATH . 'assets/production_cash/';
        
        // Pastikan folder upload ada
        if (!is_dir($this->upload_path)) {
            mkdir($this->upload_path, 0755, TRUE);
        }
    }

    public function index() {
        $azapp = $this->azapp;
        $data_header['title'] = 'Buku Kas Produksi';
        $data_header['breadcrumb'] = array('production_cash', 'production_cash_book');
        $azapp->set_data_header($data_header);

        // Tanggal default: Senin minggu ini s/d hari ini
        $monday = date('Y-m-d', strtotime('monday this week'));
        $today = date('d-m-Y');

        $datetime1 = $azapp->add_datetime();
        $datetime1->set_id("date_1");
        $datetime1->set_name("date_1");
        $datetime1->set_value(date('d-m-Y', strtotime($monday)));
        $datetime1->set_format("DD-MM-YYYY");
        if (!$this->is_admin) {
            $datetime1->set_min_date(date('Y-m-d', strtotime('-6 days')));
        }
        $data['datetime1'] = $datetime1->render();

        $datetime2 = $azapp->add_datetime();
        $datetime2->set_id("date_2");
        $datetime2->set_name("date_2");
        $datetime2->set_value($today);
        $datetime2->set_format("DD-MM-YYYY");
        $data['datetime2'] = $datetime2->render();

        // Select user produksi (untuk admin)
        if ($this->is_admin) {
            $this->db->where('idrole', 4);
            $this->db->where('status', 1);
            $data['production_users'] = $this->db->get('user');
        }

        // Ambil item kas
        if ($this->is_admin) {
            $this->db->where('status', 1);
            $data['cash_items'] = $this->db->get('production_cash_item');
        } else {
            $this->db->where('iduser', $this->iduser);
            $this->db->where('status', 1);
            $data['cash_items'] = $this->db->get('production_cash_item');
        }

        $data['is_admin'] = $this->is_admin;
        $data['today'] = date('Y-m-d');

        $this->load->helper('az_core');
        $js = az_add_js('production_cash_book/vjs_production_cash_book');
        $azapp->add_js($js);

        $view = $this->load->view('production_cash_book/v_production_cash_book', $data, true);
        $azapp->add_content($view);

        // Modal form transaksi
        $modal_data['is_admin'] = $this->is_admin;
        $modal_data['cash_items'] = $data['cash_items'];
        $v_modal = $this->load->view('production_cash_book/v_modal_transaction', $modal_data, true);

        $modal = $azapp->add_modal();
        $modal->set_id('transaction');
        $modal->set_modal_title('Transaksi Kas');
        $modal->set_modal($v_modal);
        $modal->set_action_modal(array('save-transaction' => 'Simpan'));
        $azapp->add_content($modal->render());

        echo $azapp->render();
    }

    function get_data() {
        $err_code = 0;
        $err_message = '';
        
        $date_1 = $this->input->post('date_1');
        $date_2 = $this->input->post('date_2');
        $iduser_filter = $this->input->post('iduser_filter');
        $iditem_filter = $this->input->post('iditem_filter');
        $type_filter = $this->input->post('type_filter');

        $date_1 = date('Y-m-d', strtotime($date_1));
        $date_2 = date('Y-m-d', strtotime($date_2));

        // Batasi produksi hanya 7 hari
        if (!$this->is_admin) {
            $min_date = date('Y-m-d', strtotime('-6 days'));
            if ($date_1 < $min_date) {
                $date_1 = $min_date;
            }
            $iduser_filter = $this->iduser;
        }

        if (strlen($iduser_filter) == 0) {
            $err_code++;
            $err_message = 'Harap pilih user produksi';
        }

        $data_rows = array();
        $total_debit = 0;
        $total_credit = 0;
        $opening_balance = 0;

        if ($err_code == 0) {
            // Ambil saldo awal periode
            $opening_balance = $this->get_opening_balance($iduser_filter, $date_1);

            // Ambil transaksi
            $this->db->where('production_cash_book.iduser', $iduser_filter);
            $this->db->where('production_cash_book.status', 1);
            $this->db->where('transaction_date >=', $date_1);
            $this->db->where('transaction_date <=', $date_2);
            
            if (strlen($iditem_filter) > 0) {
                $this->db->where('production_cash_book.idproduction_cash_item', $iditem_filter);
            }
            
            if ($type_filter == 'debit') {
                $this->db->where('debit >', 0);
            } else if ($type_filter == 'credit') {
                $this->db->where('credit >', 0);
            }

            $this->db->join('production_cash_item', 'production_cash_book.idproduction_cash_item = production_cash_item.idproduction_cash_item', 'left');
            $this->db->order_by('transaction_time', 'ASC');
            $query = $this->db->get('production_cash_book');

            $running_balance = $opening_balance;
            $today = date('Y-m-d');
            $i = 0;

            foreach ($query->result() as $row) {
                $running_balance = $running_balance + $row->debit - $row->credit;
                $total_debit += $row->debit;
                $total_credit += $row->credit;
                $i++;

                $can_edit = false;
                $can_delete = false;

                if ($this->is_admin) {
                    $can_edit = true;
                    $can_delete = true;
                } else if ($row->transaction_date == $today) {
                    $can_edit = true;
                    $can_delete = true;
                }

                // Foto thumbnails
                $photos = '';
                for ($p = 1; $p <= 3; $p++) {
                    $photo_field = 'photo' . $p;
                    if (strlen($row->$photo_field) > 0) {
                        $photos .= '<img class="img-item-list" style="width:40px;height:40px;object-fit:cover;margin-right:2px;cursor:pointer;" src="' . base_url() . AZAPP . 'assets/production_cash/' . $row->$photo_field . '" onclick="window.open(this.src)">';
                    }
                }

                $data_rows[] = array(
                    'no' => $i,
                    'id' => $row->idproduction_cash_book,
                    'date' => date('d-m-Y', strtotime($row->transaction_date)),
                    'time' => date('H:i', strtotime($row->transaction_time)),
                    'item_name' => $row->item_name,
                    'description' => $row->description,
                    'debit' => az_thousand_separator($row->debit),
                    'credit' => az_thousand_separator($row->credit),
                    'balance' => az_thousand_separator($running_balance),
                    'photos' => $photos,
                    'is_opening' => $row->is_opening,
                    'can_edit' => $can_edit,
                    'can_delete' => $can_delete,
                );
            }
        }

        $closing_balance = $opening_balance + $total_debit - $total_credit;

        $return = array(
            'err_code' => $err_code,
            'err_message' => $err_message,
            'data' => $data_rows,
            'opening_balance' => az_thousand_separator($opening_balance),
            'total_debit' => az_thousand_separator($total_debit),
            'total_credit' => az_thousand_separator($total_credit),
            'closing_balance' => az_thousand_separator($closing_balance),
        );

        echo json_encode($return);
    }

    function save() {
        $err_code = 0;
        $err_message = '';
        
        $id = $this->input->post('idproduction_cash_book');
        $transaction_date = $this->input->post('transaction_date');
        $iduser = $this->input->post('iduser');
        $idproduction_cash_item = $this->input->post('idproduction_cash_item');
        $description = $this->input->post('description');
        $transaction_type = $this->input->post('transaction_type');
        $amount = az_crud_number($this->input->post('amount'));

        if (strlen($id) == 0 && strlen($iduser) == 0) {
            $iduser = $this->iduser;
        }

        // Validasi tanggal untuk produksi
        if (!$this->is_admin) {
            $today = date('Y-m-d');
            if ($transaction_date != $today) {
                $err_code++;
                $err_message = 'Anda hanya dapat menambah transaksi untuk hari ini';
            }
            $iduser = $this->iduser;
        }

        if ($err_code == 0) {
            if (strlen($transaction_date) == 0) {
                $err_code++;
                $err_message = 'Tanggal wajib diisi';
            }
        }

        if ($err_code == 0) {
            if (strlen($idproduction_cash_item) == 0) {
                $err_code++;
                $err_message = 'Item kas wajib dipilih';
            }
        }

        if ($err_code == 0) {
            if (strlen($amount) == 0 || $amount == 0) {
                $err_code++;
                $err_message = 'Nominal wajib diisi';
            }
        }

        if ($err_code == 0) {
            if (strlen($description) == 0) {
                $err_code++;
                $err_message = 'Keterangan wajib diisi';
            }
        }

        // Validasi foto wajib untuk transaksi baru
        if ($err_code == 0 && strlen($id) == 0) {
            $has_photo = false;
            for ($i = 1; $i <= 3; $i++) {
                if (isset($_FILES['photo' . $i]['name']) && strlen($_FILES['photo' . $i]['name']) > 0) {
                    $has_photo = true;
                    break;
                }
            }
            if (!$has_photo) {
                $err_code++;
                $err_message = 'Foto bukti wajib diupload (minimal 1 foto)';
            }
        }

        if ($err_code == 0) {
            $this->db->trans_begin();

            $debit = 0;
            $credit = 0;
            if ($transaction_type == 'debit') {
                $debit = $amount;
            } else {
                $credit = $amount;
            }

            $data_save = array(
                'iduser' => $iduser,
                'idproduction_cash_item' => $idproduction_cash_item,
                'transaction_date' => $transaction_date,
                'transaction_time' => date('Y-m-d H:i:s'),
                'description' => $description,
                'debit' => $debit,
                'credit' => $credit,
                'is_opening' => 0,
            );

            if (strlen($id) > 0) {
                $data_save['updated'] = date('Y-m-d H:i:s');
                $data_save['updatedby'] = $this->session->userdata('username');
                $this->db->where('idproduction_cash_book', $id);
                $this->db->update('production_cash_book', $data_save);
            } else {
                $data_save['created'] = date('Y-m-d H:i:s');
                $data_save['createdby'] = $this->session->userdata('username');
                $this->db->insert('production_cash_book', $data_save);
                $id = $this->db->insert_id();
            }

            // Upload foto
            for ($i = 1; $i <= 3; $i++) {
                if (isset($_FILES['photo' . $i]['name']) && strlen($_FILES['photo' . $i]['name']) > 0) {
                    $config['upload_path'] = $this->upload_path;
                    $config['allowed_types'] = 'jpg|png|jpeg';
                    $config['max_size'] = '5120';
                    $config['encrypt_name'] = true;
                    $this->load->library('upload', $config);
                    $this->upload->initialize($config);

                    if ($this->upload->do_upload('photo' . $i)) {
                        $file_name = $this->upload->data('file_name');
                        $this->resizeImage($file_name);
                        $this->db->where('idproduction_cash_book', $id);
                        $this->db->update('production_cash_book', array('photo' . $i => $file_name));
                    }
                }
            }

            // Recalculate balance
            $this->recalculate_balance($iduser, $transaction_date);

            if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                $err_code++;
                $err_message = 'Gagal menyimpan data';
            } else {
                $this->db->trans_commit();
            }
        }

        echo json_encode(array(
            'err_code' => $err_code,
            'err_message' => $err_message,
        ));
    }

    function edit() {
        $id = $this->input->post('id');
        $err_code = 0;
        $err_message = '';
        $data = array();

        if (strlen($id) == 0) {
            $err_code++;
            $err_message = 'ID tidak valid';
        }

        if ($err_code == 0) {
            $this->db->where('idproduction_cash_book', $id);
            $this->db->where('status', 1);
            $query = $this->db->get('production_cash_book');

            if ($query->num_rows() == 0) {
                $err_code++;
                $err_message = 'Data tidak ditemukan';
            } else {
                $row = $query->row();
                
                // Validasi akses edit
                if (!$this->is_admin) {
                    if ($row->iduser != $this->iduser) {
                        $err_code++;
                        $err_message = 'Akses ditolak';
                    } else if ($row->transaction_date != date('Y-m-d')) {
                        $err_code++;
                        $err_message = 'Anda hanya dapat mengedit transaksi hari ini';
                    }
                }

                if ($err_code == 0) {
                    $type = ($row->debit > 0) ? 'debit' : 'credit';
                    $amount = ($row->debit > 0) ? $row->debit : $row->credit;

                    $data = array(
                        'idproduction_cash_book' => $row->idproduction_cash_book,
                        'iduser' => $row->iduser,
                        'idproduction_cash_item' => $row->idproduction_cash_item,
                        'transaction_date' => date('d-m-Y', strtotime($row->transaction_date)),
                        'description' => $row->description,
                        'transaction_type' => $type,
                        'amount' => az_thousand_separator($amount),
                        'photo1' => $row->photo1,
                        'photo2' => $row->photo2,
                        'photo3' => $row->photo3,
                    );
                }
            }
        }

        echo json_encode(array(
            'err_code' => $err_code,
            'err_message' => $err_message,
            'data' => $data,
        ));
    }

    function delete() {
        $id = $this->input->post('id');
        $err_code = 0;
        $err_message = '';

        if (strlen($id) == 0) {
            $err_code++;
            $err_message = 'ID tidak valid';
        }

        if ($err_code == 0) {
            $this->db->where('idproduction_cash_book', $id);
            $this->db->where('status', 1);
            $query = $this->db->get('production_cash_book');

            if ($query->num_rows() == 0) {
                $err_code++;
                $err_message = 'Data tidak ditemukan';
            } else {
                $row = $query->row();
                
                if (!$this->is_admin) {
                    if ($row->iduser != $this->iduser) {
                        $err_code++;
                        $err_message = 'Akses ditolak';
                    } else if ($row->transaction_date != date('Y-m-d')) {
                        $err_code++;
                        $err_message = 'Anda hanya dapat menghapus transaksi hari ini';
                    }
                }

                if ($err_code == 0) {
                    // Hapus file foto
                    for ($i = 1; $i <= 3; $i++) {
                        $photo = 'photo' . $i;
                        if (strlen($row->$photo) > 0 && file_exists($this->upload_path . $row->$photo)) {
                            unlink($this->upload_path . $row->$photo);
                        }
                    }

                    $this->db->where('idproduction_cash_book', $id);
                    $this->db->update('production_cash_book', array('status' => 0));
                    
                    $this->recalculate_balance($row->iduser, $row->transaction_date);
                }
            }
        }

        echo json_encode(array(
            'err_code' => $err_code,
            'err_message' => $err_message,
        ));
    }

    function print_report() {
        $date_1 = $this->input->get('date_1');
        $date_2 = $this->input->get('date_2');
        $iduser_filter = $this->input->get('iduser_filter');
        $iditem_filter = $this->input->get('iditem_filter');
        $type_filter = $this->input->get('type_filter');

        $date_1 = date('Y-m-d', strtotime($date_1));
        $date_2 = date('Y-m-d', strtotime($date_2));

        if (!$this->is_admin) {
            $min_date = date('Y-m-d', strtotime('-6 days'));
            if ($date_1 < $min_date) {
                $date_1 = $min_date;
            }
            $iduser_filter = $this->iduser;
        }

        $opening_balance = $this->get_opening_balance($iduser_filter, $date_1);

        $this->db->where('production_cash_book.iduser', $iduser_filter);
        $this->db->where('production_cash_book.status', 1);
        $this->db->where('transaction_date >=', $date_1);
        $this->db->where('transaction_date <=', $date_2);
        
        if (strlen($iditem_filter) > 0) {
            $this->db->where('production_cash_book.idproduction_cash_item', $iditem_filter);
        }
        if ($type_filter == 'debit') {
            $this->db->where('debit >', 0);
        } else if ($type_filter == 'credit') {
            $this->db->where('credit >', 0);
        }

        $this->db->join('production_cash_item', 'production_cash_book.idproduction_cash_item = production_cash_item.idproduction_cash_item', 'left');
        $this->db->join('user', 'production_cash_book.iduser = user.iduser', 'left');
        $this->db->order_by('transaction_time', 'ASC');
        $data['rows'] = $this->db->get('production_cash_book');

        $this->db->where('iduser', $iduser_filter);
        $data['user'] = $this->db->get('user')->row();

        $data['date_1'] = $date_1;
        $data['date_2'] = $date_2;
        $data['opening_balance'] = $opening_balance;

        $this->load->view('production_cash_book/v_print_cash_book', $data);
    }

    function download_pdf() {
        // Sama seperti print tapi output PDF via DomPDF
        $date_1 = $this->input->get('date_1');
        $date_2 = $this->input->get('date_2');
        $iduser_filter = $this->input->get('iduser_filter');
        $iditem_filter = $this->input->get('iditem_filter');
        $type_filter = $this->input->get('type_filter');

        $date_1 = date('Y-m-d', strtotime($date_1));
        $date_2 = date('Y-m-d', strtotime($date_2));

        if (!$this->is_admin) {
            $min_date = date('Y-m-d', strtotime('-6 days'));
            if ($date_1 < $min_date) {
                $date_1 = $min_date;
            }
            $iduser_filter = $this->iduser;
        }

        $opening_balance = $this->get_opening_balance($iduser_filter, $date_1);

        $this->db->where('production_cash_book.iduser', $iduser_filter);
        $this->db->where('production_cash_book.status', 1);
        $this->db->where('transaction_date >=', $date_1);
        $this->db->where('transaction_date <=', $date_2);
        
        if (strlen($iditem_filter) > 0) {
            $this->db->where('production_cash_book.idproduction_cash_item', $iditem_filter);
        }
        if ($type_filter == 'debit') {
            $this->db->where('debit >', 0);
        } else if ($type_filter == 'credit') {
            $this->db->where('credit >', 0);
        }

        $this->db->join('production_cash_item', 'production_cash_book.idproduction_cash_item = production_cash_item.idproduction_cash_item', 'left');
        $this->db->join('user', 'production_cash_book.iduser = user.iduser', 'left');
        $this->db->order_by('transaction_time', 'ASC');
        $data['rows'] = $this->db->get('production_cash_book');

        $this->db->where('iduser', $iduser_filter);
        $data['user'] = $this->db->get('user')->row();

        $data['date_1'] = $date_1;
        $data['date_2'] = $date_2;
        $data['opening_balance'] = $opening_balance;

        $html = $this->load->view('production_cash_book/v_pdf_cash_book', $data, true);

        // DomPDF
        $this->load->library('dompdf_gen');
        $this->dompdf->load_html($html);
        $this->dompdf->set_paper('A4', 'landscape');
        $this->dompdf->render();
        $filename = 'Buku_Kas_Produksi_' . $data['user']->name . '_' . date('Ymd', strtotime($date_1)) . '-' . date('Ymd', strtotime($date_2));
        $this->dompdf->stream($filename . '.pdf', array('Attachment' => true));
    }

    // === HELPER FUNCTIONS ===

    private function get_opening_balance($iduser, $date) {
        $monday = date('Y-m-d', strtotime('monday', strtotime($date)));
        
        $this->db->where('iduser', $iduser);
        $this->db->where('period_start', $monday);
        $this->db->where('status', 1);
        $query = $this->db->get('production_cash_balance');

        if ($query->num_rows() > 0) {
            return $query->row()->opening_balance;
        }

        // Jika belum ada, hitung dari saldo akhir minggu sebelumnya
        $prev_sunday = date('Y-m-d', strtotime($monday . ' -1 day'));
        $prev_opening = $this->get_opening_balance_recursive($iduser, $prev_sunday);
        
        $this->db->where('iduser', $iduser);
        $this->db->where('transaction_date <=', $prev_sunday);
        $this->db->where('status', 1);
        $this->db->select('SUM(debit) as total_debit, SUM(credit) as total_credit');
        $prev_trx = $this->db->get('production_cash_book')->row();

        return $prev_opening + ($prev_trx->total_debit ? $prev_trx->total_debit : 0) - ($prev_trx->total_credit ? $prev_trx->total_credit : 0);
    }

    private function get_opening_balance_recursive($iduser, $date) {
        $monday = date('Y-m-d', strtotime('monday', strtotime($date)));
        
        $this->db->where('iduser', $iduser);
        $this->db->where('period_start', $monday);
        $this->db->where('status', 1);
        $query = $this->db->get('production_cash_balance');

        if ($query->num_rows() > 0) {
            return $query->row()->opening_balance;
        }

        return 0;
    }

    private function recalculate_balance($iduser, $from_date) {
        // Recalculate running balance dari tanggal tertentu
        $opening = $this->get_opening_balance($iduser, $from_date);
        
        $this->db->where('iduser', $iduser);
        $this->db->where('transaction_date >=', $from_date);
        $this->db->where('status', 1);
        $this->db->order_by('transaction_time', 'ASC');
        $query = $this->db->get('production_cash_book');

        $balance = $opening;
        foreach ($query->result() as $row) {
            $balance = $balance + $row->debit - $row->credit;
            $this->db->where('idproduction_cash_book', $row->idproduction_cash_book);
            $this->db->update('production_cash_book', array('balance' => $balance));
        }
    }

    public function resizeImage($filename) {
        $source_path = $this->upload_path . $filename;
        $target_path = $this->upload_path;
        $config_manip = array(
            'image_library' => 'gd2',
            'source_image' => $source_path,
            'new_image' => $target_path,
            'maintain_ratio' => TRUE,
            'width' => 800,
        );
        $this->load->library('image_lib', $config_manip);
        $this->image_lib->resize();
        $this->image_lib->clear();
    }
}