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

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

    /**
     * Liste des transferts
     */
    public function index()
    {
        $this->auth_lib->require_permission('transfer_view');

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

        $page   = max(1, (int) $this->input->get('page'));
        $limit  = 20;
        $offset = ($page - 1) * $limit;

        $data = [
            'title'     => 'Transferts Internes',
            'transfers' => $this->Cashbox_model->get_transfers($filters, $limit, $offset),
            'total'     => $this->Cashbox_model->count_transfers($filters),
            'cashboxes' => $this->Cashbox_model->get_all(['is_active' => 1]),
            'filters'   => $filters,
            'page'      => $page,
            'limit'     => $limit,
        ];

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

    /**
     * Créer un transfert (approvisionnement de caisse)
     */
    public function create()
    {
        $this->auth_lib->require_permission('transfer_create');

        $cashboxes = $this->Cashbox_model->get_all(['is_active' => 1]);

        $data = [
            'title'     => 'Nouveau Transfert',
            'cashboxes' => $cashboxes,
            'reference' => $this->Cashbox_model->next_transfer_reference(),
        ];

        if ($this->input->method() === 'post') {
            $this->form_validation->set_rules('source_cashbox_id', 'Caisse source', 'required|integer');
            $this->form_validation->set_rules('dest_cashbox_id', 'Caisse destination', 'required|integer|differs[source_cashbox_id]');
            $this->form_validation->set_rules('amount', 'Montant', 'required|numeric|greater_than[0]');
            $this->form_validation->set_rules('transfer_date', 'Date', 'required');

            $this->form_validation->set_message('differs', 'La caisse destination doit être différente de la source.');

            if ($this->form_validation->run() === TRUE) {
                $transfer_data = [
                    'reference'         => $this->Cashbox_model->next_transfer_reference(),
                    'transfer_date'     => $this->input->post('transfer_date'),
                    'source_cashbox_id' => $this->input->post('source_cashbox_id'),
                    'dest_cashbox_id'   => $this->input->post('dest_cashbox_id'),
                    'amount'            => $this->input->post('amount'),
                    'currency'          => 'KMF',
                    'notes'             => $this->input->post('notes', TRUE),
                    'status'            => 'pending',
                    'created_by'        => $this->auth_lib->user_id(),
                ];

                // Upload justificatif
                if ( ! empty($_FILES['receipt']['name'])) {
                    $upload_path = './uploads/replenishments/';
                    if ( ! is_dir($upload_path)) {
                        mkdir($upload_path, 0777, TRUE);
                    }

                    $this->load->library('upload', [
                        'upload_path'   => $upload_path,
                        'allowed_types' => 'jpg|jpeg|png|pdf',
                        'max_size'      => 5120,
                        'file_name'     => $transfer_data['reference'] . '_' . time(),
                    ]);

                    if ($this->upload->do_upload('receipt')) {
                        $transfer_data['receipt_path'] = 'uploads/replenishments/' . $this->upload->data('file_name');
                    }
                }

                $new_id = $this->Cashbox_model->create_transfer($transfer_data);

                $this->auth_lib->log_action(
                    $this->auth_lib->user_id(), 'transfer_created', 'transfers', $new_id,
                    $transfer_data['reference'] . ' | ' . number_format($transfer_data['amount']) . ' KMF'
                );

                $this->session->set_flashdata('success', 'Transfert ' . $transfer_data['reference'] . ' créé. En attente de validation.');
                redirect('transfers');
            }
        }

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

    /**
     * Détail d'un transfert
     */
    public function view($id)
    {
        $this->auth_lib->require_permission('transfer_view');

        $transfer = $this->Cashbox_model->get_transfer($id);
        if ( ! $transfer) show_404();

        $data = [
            'title'    => 'Transfert ' . $transfer->reference,
            'transfer' => $transfer,
        ];

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

    /**
     * Valider un transfert
     */
    public function validate($id)
    {
        $this->auth_lib->require_permission('transfer_validate');

        $success = $this->Cashbox_model->validate_transfer($id, $this->auth_lib->user_id());

        if ($success) {
            $transfer = $this->Cashbox_model->get_transfer($id);
            $this->auth_lib->log_action(
                $this->auth_lib->user_id(), 'transfer_validated', 'transfers', $id,
                $transfer->reference . ' | ' . number_format($transfer->amount) . ' KMF'
            );
            $this->session->set_flashdata('success', 'Transfert validé. Soldes mis à jour.');
        } else {
            $this->session->set_flashdata('error', 'Impossible de valider ce transfert.');
        }

        redirect('transfers/view/' . $id);
    }

    /**
     * Rejeter un transfert
     */
    public function reject($id)
    {
        $this->auth_lib->require_permission('transfer_validate');

        $this->Cashbox_model->reject_transfer($id, $this->auth_lib->user_id());

        $this->auth_lib->log_action(
            $this->auth_lib->user_id(), 'transfer_rejected', 'transfers', $id
        );

        $this->session->set_flashdata('success', 'Transfert rejeté.');
        redirect('transfers/view/' . $id);
    }
}
