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

class Dashboard extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('auth_lib');
        $this->load->helper(['url']);
        $this->auth_lib->require_login();
    }

    public function index()
    {
        $this->load->model('Expense_model');
        $this->load->model('Request_model');
        $this->load->model('Cashbox_model');
        $this->load->model('Statement_model');

        $is_manager  = $this->auth_lib->is_manager_or_admin();
        $location_id = $this->auth_lib->location_id();
        $loc_filter  = ($is_manager) ? null : $location_id;

        // --- KPIs ---
        $monthly_expenses   = $this->Expense_model->get_monthly_total($loc_filter);
        $pending_expenses   = $this->Expense_model->count_pending($loc_filter);
        $pending_requests   = $this->Request_model->count_pending($loc_filter);
        $partner_balance    = $this->Statement_model->get_current_balance();
        $total_treasury     = 0;

        // Caisses accessibles
        $cashboxes = $this->Cashbox_model->get_accessible($location_id, $is_manager);
        foreach ($cashboxes as $cb) {
            $total_treasury += (float) $cb->current_balance;
        }

        // --- Dernières dépenses ---
        $recent_filters = [];
        if ($loc_filter) $recent_filters['user_location_id'] = $loc_filter;
        $recent_expenses = $this->Expense_model->get_list($recent_filters, 5);

        // --- Demandes en attente ---
        $pending_req_list = $this->Request_model->get_list(['status' => 'pending'], 5);

        // --- Dépenses en attente de validation ---
        $pending_exp_list = $this->Expense_model->get_list(
            array_merge(['status' => 'pending'], $loc_filter ? ['user_location_id' => $loc_filter] : []), 
            5
        );

        // --- Dépenses par catégorie (mois en cours) ---
        $expenses_by_category = $this->_get_expenses_by_category($loc_filter);

        // --- Dépenses par localisation (mois en cours) ---
        $expenses_by_location = $this->_get_expenses_by_location();

        $data = [
            'title'               => 'Tableau de Bord',
            'monthly_expenses'    => $monthly_expenses,
            'pending_expenses'    => $pending_expenses,
            'pending_requests'    => $pending_requests,
            'partner_balance'     => $partner_balance,
            'total_treasury'      => $total_treasury,
            'cashboxes'           => $cashboxes,
            'recent_expenses'     => $recent_expenses,
            'pending_req_list'    => $pending_req_list,
            'pending_exp_list'    => $pending_exp_list,
            'expenses_by_category'=> $expenses_by_category,
            'expenses_by_location'=> $expenses_by_location,
            'is_manager'          => $is_manager,
        ];

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

    private function _get_expenses_by_category($location_id = null)
    {
        $this->db
            ->select('expense_categories.label, SUM(expenses.amount) AS total, COUNT(*) AS count')
            ->join('expense_categories', 'expense_categories.id = expenses.category_id')
            ->where('expenses.expense_date >=', date('Y-m-01'))
            ->where_in('expenses.status', ['validated', 'batched'])
            ->group_by('expense_categories.label')
            ->order_by('total', 'DESC');

        if ($location_id) {
            $this->db->where('expenses.location_id', $location_id);
        }

        return $this->db->get('expenses')->result();
    }

    private function _get_expenses_by_location()
    {
        return $this->db
            ->select('locations.name, SUM(expenses.amount) AS total, COUNT(*) AS count')
            ->join('locations', 'locations.id = expenses.location_id')
            ->where('expenses.expense_date >=', date('Y-m-01'))
            ->where_in('expenses.status', ['validated', 'batched'])
            ->group_by('locations.name')
            ->order_by('total', 'DESC')
            ->get('expenses')
            ->result();
    }
}
