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

class Statements extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('auth_lib');
        $this->load->library('form_validation');
        $this->load->model('Statement_model');
        $this->load->model('Cashbox_model');
        $this->load->helper(['url', 'form']);
        $this->auth_lib->require_login();
    }

    /**
     * Relevé du compte partenaire (Owner Running Account)
     */
    public function index()
    {
        $this->auth_lib->require_permission('partner_view');

        $filters = [
            'type'      => $this->input->get('type'),
            'date_from' => $this->input->get('date_from'),
            'date_to'   => $this->input->get('date_to'),
            'search'    => $this->input->get('search'),
        ];

        // Récupérer les transactions
        $transactions = $this->Statement_model->get_statement($filters, 200);

        // Calculer le running balance pour l'affichage
        // Si filtre date_from, on commence avec le solde antérieur
        $running_balance = 0;
        if ( ! empty($filters['date_from'])) {
            $running_balance = $this->Statement_model->get_balance_before($filters['date_from']);
        }

        // Ajouter le running balance à chaque transaction
        foreach ($transactions as &$tx) {
            $running_balance = $running_balance + (float) $tx->credit - (float) $tx->debit;
            $tx->running_balance = $running_balance;
        }

        $totals = $this->Statement_model->get_totals($filters);

        $data = [
            'title'          => 'Compte Partenaire',
            'transactions'   => $transactions,
            'totals'         => $totals,
            'current_balance'=> $this->Statement_model->get_current_balance(),
            'filters'        => $filters,
        ];

        $this->load->view('templates/header', $data);
        $this->load->view('statements/index', $data);
        $this->load->view('templates/footer');
    }

    /**
     * Enregistrer un cash advance
     */
    public function cash_advance()
    {
        $this->auth_lib->require_permission('partner_manage');

        // Trouver le compte bancaire
        $bank = $this->_get_bank_cashbox();

        $data = [
            'title'     => 'Enregistrer un Cash Advance',
            'reference' => $this->Statement_model->next_advance_reference(),
            'bank'      => $bank,
        ];

        if ($this->input->method() === 'post') {
            $this->form_validation->set_rules('amount', 'Montant', 'required|numeric|greater_than[0]');
            $this->form_validation->set_rules('date', 'Date', 'required');
            $this->form_validation->set_rules('description', 'Description', 'required|trim|min_length[5]');

            if ($this->form_validation->run() === TRUE) {
                $advance_data = [
                    'date'        => $this->input->post('date'),
                    'reference'   => $this->Statement_model->next_advance_reference(),
                    'description' => $this->input->post('description', TRUE),
                    'amount'      => $this->input->post('amount'),
                ];

                $tx_id = $this->Statement_model->record_cash_advance(
                    $advance_data,
                    $bank->id,
                    $this->auth_lib->user_id()
                );

                if ($tx_id) {
                    $this->auth_lib->log_action(
                        $this->auth_lib->user_id(), 'cash_advance_recorded', 'partner', $tx_id,
                        $advance_data['reference'] . ' | ' . number_format($advance_data['amount']) . ' KMF'
                    );

                    $this->session->set_flashdata('success',
                        'Cash advance ' . $advance_data['reference'] . ' enregistré : ' .
                        number_format($advance_data['amount'], 0, ',', ' ') . ' KMF. ' .
                        'Le compte bancaire a été crédité.');
                    redirect('statements');
                } else {
                    $data['error'] = 'Erreur lors de l\'enregistrement.';
                }
            }
        }

        $this->load->view('templates/header', $data);
        $this->load->view('statements/cash_advance', $data);
        $this->load->view('templates/footer');
    }

    /**
     * Enregistrer un ajustement manuel
     */
    public function adjustment()
    {
        $this->auth_lib->require_permission('partner_manage');

        $data = [
            'title' => 'Ajustement du Compte Partenaire',
        ];

        if ($this->input->method() === 'post') {
            $this->form_validation->set_rules('date', 'Date', 'required');
            $this->form_validation->set_rules('reference', 'Référence', 'required|trim');
            $this->form_validation->set_rules('description', 'Description', 'required|trim|min_length[5]');
            $this->form_validation->set_rules('direction', 'Sens', 'required|in_list[debit,credit]');
            $this->form_validation->set_rules('amount', 'Montant', 'required|numeric|greater_than[0]');

            if ($this->form_validation->run() === TRUE) {
                $direction = $this->input->post('direction');
                $amount    = $this->input->post('amount');

                $adj_data = [
                    'date'        => $this->input->post('date'),
                    'reference'   => $this->input->post('reference', TRUE),
                    'description' => $this->input->post('description', TRUE),
                    'debit'       => ($direction === 'debit')  ? $amount : 0,
                    'credit'      => ($direction === 'credit') ? $amount : 0,
                ];

                $tx_id = $this->Statement_model->record_adjustment(
                    $adj_data, $this->auth_lib->user_id()
                );

                if ($tx_id) {
                    $this->auth_lib->log_action(
                        $this->auth_lib->user_id(), 'partner_adjustment', 'partner', $tx_id,
                        $adj_data['reference'] . ' | ' . $direction . ' ' . number_format($amount) . ' KMF'
                    );

                    $this->session->set_flashdata('success', 'Ajustement enregistré.');
                    redirect('statements');
                }
            }
        }

        $this->load->view('templates/header', $data);
        $this->load->view('statements/adjustment', $data);
        $this->load->view('templates/footer');
    }

    /**
     * Détail d'une transaction
     */
    public function view($id)
    {
        $this->auth_lib->require_permission('partner_view');

        $transaction = $this->Statement_model->get($id);
        if ( ! $transaction) show_404();

        $data = [
            'title'       => 'Transaction ' . $transaction->reference,
            'transaction' => $transaction,
        ];

        $this->load->view('templates/header', $data);
        $this->load->view('statements/view', $data);
        $this->load->view('templates/footer');
    }

    // -------------------------------------------------------
    // PRIVATE
    // -------------------------------------------------------

    /**
     * Trouver le compte bancaire principal
     */
    private function _get_bank_cashbox()
    {
        $cashboxes = $this->Cashbox_model->get_all(['type' => 'bank']);
        if (empty($cashboxes)) {
            show_error('Aucun compte bancaire configuré dans le système.');
        }
        return $cashboxes[0];
    }
}
