<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of admistrator
 *
 * @author pc mart ltd
 */
class Dashboard extends Client_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('admin_model');
        $this->load->model('invoice_model');
        $this->load->model('client_model');
        $this->load->model('items_model');
        $this->load->model('finance_report_model');
    }

    public function index($action = NULL)
    {
        $clientId = (int) ($this->session->userdata('client_id') ?? 0);
        if (!$clientId) {
            $userId = (int) $this->session->userdata('user_id');

            // Client account links are stored on account_details.company.
            $accountInfo = $this->db
                ->select('company')
                ->where('user_id', $userId)
                ->get('tbl_account_details')
                ->row();

            $clientId = !empty($accountInfo->company) ? (int) $accountInfo->company : 0;

            // Fallback for older data where client contact is stored in tbl_client.primary_contact.
            if (!$clientId) {
                $clientInfo = $this->db
                    ->select('client_id')
                    ->where('primary_contact', $userId)
                    ->get('tbl_client')
                    ->row();
                $clientId = !empty($clientInfo->client_id) ? (int) $clientInfo->client_id : 0;
            }

            if ($clientId) {
                $this->session->set_userdata('client_id', $clientId);
            }
        }

        $data['title'] = lang('dashboard');
        $data['page_title'] = lang('dashboard');
        $data['breadcrumbs'] = lang('dashboard');
        $data['client_transactions'] = [];
        $data['total_income_amount'] = 0;
        $data['total_expense_amount'] = 0;
        $data['client_project_count'] = 0;
        $data['client_invoice_count'] = 0;
        $data['client_projects'] = array();

        if ($clientId) {
            $this->invoice_model->_table_name = "tbl_transactions";
            $this->invoice_model->_order_by = "transactions_id";
            $data['client_transactions'] = $this->invoice_model->get_by(array('paid_by' => $clientId), FALSE);

            $finance_rollup = $this->finance_report_model->get_client_finance_rollup($clientId);
            $data['total_income_amount'] = !empty($finance_rollup['income_total']) ? (float) $finance_rollup['income_total'] : 0;
            $data['total_expense_amount'] = !empty($finance_rollup['expense_total']) ? (float) $finance_rollup['expense_total'] : 0;
            $data['client_project_count'] = (int) $this->db->where('client_id', $clientId)->count_all_results('tbl_project');
            $data['client_invoice_count'] = (int) $this->db->where('client_id', $clientId)->count_all_results('tbl_invoices');
            $data['client_projects'] = $this->db
                ->where('client_id', $clientId)
                ->order_by('project_id', 'desc')
                ->limit(6)
                ->get('tbl_project')
                ->result();
        }

        $this->render('client/dashboard', $data);
    }

    public function reset_cache()
    {
        $this->load->driver('cache', array('adapter' => 'file'));

        if (isset($this->cache) && method_exists($this->cache, 'clean')) {
            $this->cache->clean();
        }

        $cachePath = APPPATH . 'cache/';
        if (is_dir($cachePath)) {
            $cacheFiles = glob($cachePath . '*');
            if (!empty($cacheFiles)) {
                foreach ($cacheFiles as $filePath) {
                    $baseName = basename($filePath);
                    if (in_array($baseName, array('index.html', '.htaccess'), true)) {
                        continue;
                    }
                    if (is_file($filePath)) {
                        @unlink($filePath);
                    }
                }
            }
        }

        set_message('success', lang('application_cache_reset'));
        if (!empty($_SERVER['HTTP_REFERER'])) {
            redirect($_SERVER['HTTP_REFERER']);
        }
        redirect('client/dashboard');
    }

    function invoice_totals_per_currency()
    {
        $invoices_info = $this->db->where('inv_deleted', 'No')->get('tbl_invoices')->result();
        $paid = $due = array();
        $currency = 'USD';
        $symbol = array();
        foreach ($invoices_info as $v_invoices) {
            if (!isset($paid[$v_invoices->currency])) {
                $paid[$v_invoices->currency] = 0;
            }
            if (!isset($due[$v_invoices->currency])) {
                $due[$v_invoices->currency] = 0;
            }
            $paid[$v_invoices->currency] += $this->invoice_model->get_invoice_paid_amount($v_invoices->invoices_id);
            $due[$v_invoices->currency] += $this->invoice_model->get_invoice_due_amount($v_invoices->invoices_id);
            $currency = $this->admin_model->check_by(array('code' => $v_invoices->currency), 'tbl_currencies');
            $symbol[$v_invoices->currency] = $currency->symbol;
        }
        return array("paid" => $paid, "due" => $due, "symbol" => $symbol);
    }

    public function get_yearly_overview($year)
    {// this function is to create get monthy recap report
        for ($i = 1; $i <= 12; $i++) { // query for months
            if ($i >= 1 && $i <= 9) { // if i<=9 concate with Mysql.becuase on Mysql query fast in two digit like 01.
                $month = '0' . $i;
            } else {
                $month = $i;
            }
            $yearly_report[$i] = $this->admin_model->calculate_amount($year, $month); // get all report by start date and in date
        }
        return $yearly_report; // return the result
    }

    public function set_language($lang)
    {
        $check_languages = get_row('tbl_languages', array('active' => 1, 'name' => $lang));
        if (!empty($check_languages)) {
            $this->session->set_userdata('lang', $lang);
        } else {
            set_message('error', lang('nothing_to_display'));
        }
        if (empty($_SERVER['HTTP_REFERER'])) {
            redirect('client/dashboard');
        } else {
            redirect($_SERVER['HTTP_REFERER']);
        }
    }

    public function announcements_details($id)
    {
        redirect('client/announcements/view_announcements_details/' . (int) $id);
    }

}
