<?php

/*
|--------------------------------------------------------------------------
| Controller
|--------------------------------------------------------------------------
|
*/

if (!defined('APP_RUN')) {
    exit('No direct access allowed');
}

_auth();

$app->emit('admin_controller_started');

$ui->assign('_title', $_L['Dashboard'] . '- ' . $config['CompanyName']);
$user = User::_info();
$ui->assign('user', $user);
$ui->assign('selected_navigation', 'dashboard');

$ui->assign('base_datos_para_socket', DB_NAME);
$ui->assign('config_whatsapp_other_id_para_socket', empty($user["config_whatsapp_other_id"]) == true ? "No_existe" : $user["config_whatsapp_other_id"] );
$ui->assign('url_ir_chat_empleado', U . "social/social-chat-employee");
$ui->assign('url_ir_chat_admin', U . "social/social-chat");
$ui->assign('url_ir_chat_crm', U . "social/chat-crm");

$ui->assign('url_base_plantilla_admintpl', U);


$action = route(1);

if ($action == '') {
    $action = isset($config['dashboard']) ? $config['dashboard'] : 'canvas';
}

/*if ($user->roleid == "3") {
   $action = "dashboard_employee";
}*/

switch ($action) {

   /* case 'dashboard_employee' :

           /*$invoices = ORM::for_table('sys_invoices')
            ->limit(5)
            ->order_by_desc('id')
            ->find_many();
            $ui->assign('invoices', $invoices);

            break;*/

        case 'canvas':

                    $app->emit('dashboard');

                    $all_data_access = false;

                    $db_version = $config['version'] ?? null;
                    $manifest = require APP_SYSTEM_PATH . '/manifest.php';
                    if ($manifest['system']['version'] != $db_version) {
                        redirect_to('updating/schema/');
                    }

                     
                    $all_items = [];
                    $item_sold = [];


                    //Invoices Employee
                    $empleados_facturas = [];

                    /* $all_invoice_items = InvoiceItem::where('itemcode', '!=', '')
                    ->whereBetween('created_at', [$startDate . " 00:00:01", $endDate . " 23:59:59"])
                    ->get()
                    ->groupBy('itemcode')
                    ->all(); */

                    //print_r(json_encode($user)); exit;

                    $fecha_inicio = date("Y-m-01");
                    $fecha_final =   date("Y-m-t", mktime(0, 0, 0, $month, 1, $year));

                    //query basada este codigo
                    //SELECT SUM(total) AS 'total_amount', SUM(credit) AS 'total_pain', SUM(total-credit) AS 'total_amout_due' FROM `sys_invoices` WHERE date BETWEEN '2024-07-01' and '2024-07-31' AND type="Invoice" AND aid != 0 GROUP BY `aid` asc

                    $all_invoice_items = Invoice::where('type', 'Invoice')
                    ->where('aid', "!=" , '0')
                    //->whereBetween('date', [$fecha_inicio , $fecha_final ])
                    ->whereBetween('datepaid', [$fecha_inicio ." 00:00:01" , $fecha_final . " 23:59:59" ])
                    ->orderBy('aid', 'asc')
                    ->get()
                    ->groupBy('aid')
                    ->all();

                    //$invoices = Invoice::whereBetween('date', [$fechaInicio, $fechaFin]);

 
                    /* foreach ($all_invoice_items as $key => $value) {
                        $count = count($value); //total de facturas
                        $total_amount    = 0; //total de toda las factura
                        $total_pain      = 0; //total de todo lo que me pagan de la factura
                        $total_amout_due = 0; //total de todo lo que me deben
 
                        //$total = 0;

                        $id_usuario = 0;

                        foreach ($value as $item) {

                            $total_amount += $item->total;
                            $total_pain += $item->credit;
                            $total_amout_due += $item->total - $item->credit;
                            
                            $id_usuario = $item->aid;

                        }

 
                        $owners = ORM::for_table('sys_users')->find($id_usuario);
                        $fullname=$owners->fullname;

                        $empleados_facturas[] = [
                            'name'              => $fullname,
                            'id_usuario'        => $id_usuario,
                            'cantidad_facturas' => $count,
                            'total_amount'      => $total_amount,
                            'total_pain'        => $total_pain,
                            'total_amout_due'   => $total_amout_due,
                            //'total'             => formatCurrency($total * $count, $config['home_currency']),
                        ];
                    } */

                    $fecha_inicio_con = $fecha_inicio ." 00:00:01";
                    $fecha_fin_con = $fecha_final ." 23:59:59";

                    
                    $mysqli = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
                    $mysqli->set_charset("utf8");

                    

                    $data_template_invoices = $mysqli->query("SELECT 
                                                                SUM(STra.amount) AS total_pain,
                                                                SU.fullname

                                                            FROM `sys_transactions` AS STra 
                                                            LEFT JOIN `sys_users` AS SU ON STra.staff_id_pago = SU.id
                                                            WHERE 
                                                            STra.updated_at between '$fecha_inicio_con' and '$fecha_fin_con' 
                                                            AND STra.`type`='Income' AND  STra.staff_id_pago is not null 
                                                            GROUP BY STra.staff_id_pago")->fetch_all(MYSQLI_ASSOC) ;

                    //echo json_encode($data_template_invoices); exit;
                                                            
        
                    //$invoices = Invoice::whereBetween('date', [$fechaInicio, $fechaFin]);

        
                    /* foreach ($all_invoice_items as $key => $value) {
                        $count = count($value); //total de facturas
                        $total_amount    = 0; //total de toda las factura
                        $total_pain      = 0; //total de todo lo que me pagan de la factura
                        $total_amout_due = 0; //total de todo lo que me deben
        
                        //$total = 0;

                        $id_usuario = 0;

                        foreach ($value as $item) {

                            $total_amount += $item->total;
                            $total_pain += $item->credit;
                            $total_amout_due += $item->total - $item->credit;
                            
                            $id_usuario = $item->aid;

                        }

        
                        $owners = ORM::for_table('sys_users')->find($id_usuario);
                        $fullname=$owners->fullname;

                        $empleados_facturas[] = [
                            'name'              => $fullname,
                            'id_usuario'        => $id_usuario,
                            'cantidad_facturas' => $count,
                            'total_amount'      => $total_amount,
                            'total_pain'        => $total_pain,
                            'total_amout_due'   => $total_amout_due,
                            //'total'             => formatCurrency($total * $count, $config['home_currency']),
                        ];
                    } */
                    //Fin de employee

                    $empleados_facturas_html = '';

                    $invoices_employees_cantidad = 0;
                    $invoices_employees_amount = 0;
                    $invoices_employees_pain = 0;
                    $invoices_employees_amount_due = 0;

                    foreach ($data_template_invoices as $ds) {

                        //$fullname   +=  $ds['fullname'];
                        //$invoices_employees_amount     +=  $ds['total_amount'];
                        $invoices_employees_pain       +=  $ds['total_pain'];
                        //$invoices_employees_amount_due +=  $ds['total_amout_due'];

                        $empleados_facturas_html .= '<tr  >';
                        $empleados_facturas_html .= '<td class="h6"><strong>' . $ds['fullname'] . '</strong> <br></td>';
                        //$empleados_facturas_html .= '<td class="h6">' . $ds['cantidad_facturas'] . '</td>';
                        //$empleados_facturas_html .= '<td class="h6">' . formatCurrency($ds['total_amount'], $ds['currency_iso_code']) . '</td>';
                        $empleados_facturas_html .= '<td class="text-success h6"><strong>' . formatCurrency($ds['total_pain'], $ds['currency_iso_code']) . '</strong></td>';
                        //$empleados_facturas_html .= '<td class="text-danger h6"><strong>' . formatCurrency($ds['total_amout_due'], $ds['currency_iso_code']) . '</strong></td>';
                        $empleados_facturas_html .= '</tr>';
                    }

                    $empleados_facturas_html .= '<tr >';
                    $empleados_facturas_html .= '<td class="h6"><strong>' . "Total:" . '</strong> <br></td>';
                    //$empleados_facturas_html .= '<td class="h6">' . $invoices_employees_cantidad . '</td>';
                    //$empleados_facturas_html .= '<td class="h6">' . formatCurrency($invoices_employees_amount, $ds['currency_iso_code']) . '</td>';
                    $empleados_facturas_html .= '<td class="text-success h6"><strong>' . formatCurrency($invoices_employees_pain, $ds['currency_iso_code']) . '</strong></td>';
                    //$empleados_facturas_html .= '<td class="text-danger h6"><strong>' . formatCurrency($invoices_employees_amount_due, $ds['currency_iso_code']) . '</strong></td>';
                    $empleados_facturas_html .= '</tr>';
                    //Fin de employee

                    $ui->assign('empleados_facturas', $data_template_invoices);
                    $ui->assign('empleados_facturas_fechas', $fecha_inicio . " / " . $fecha_final);
                    //print_r(json_encode($empleados_facturas)); exit;

                    
                    //esto le pertenece al cliente
                    if (!has_access($user->roleid, 'reports')) {


                        /*$invoices = ORM::for_table('sys_invoices')
                        ->where('aid', $user->id)
                        ->limit(5)
                        ->order_by_desc('id')
                        ->find_many();*/
                        $from=date('Y-m-d');
                        $to=date('Y-m-d');

                        $fecha= date("Y-m-d");
                        $diaInicio="Monday";
                        $diaFin="Sunday";
                        $strFecha = strtotime($fecha);
                        $fechaInicio = date('Y-m-d',strtotime('last '.$diaInicio,$strFecha));
                        $fechaFin = date('Y-m-d',strtotime('next '.$diaFin,$strFecha));
                        if(date("l",$strFecha)==$diaInicio){
                            $fechaInicio= date("Y-m-d",$strFecha);
                        }
                        if(date("l",$strFecha)==$diaFin){
                            $fechaFin= date("Y-m-d",$strFecha);
                        }

                        $invoices = Invoice::whereBetween('date', [$fechaInicio, $fechaFin]);

                        $invoices = $invoices->where('aid', $user->id)->get();


                        $appointments = ORM::for_table('app_appointments')
                        ->where('admin_id', $user->id)
                        ->limit(5)
                        ->order_by_desc('id')
                        ->find_many();

                        $ui->assign('invoices', $invoices);
                        $ui->assign('date_start', $fechaInicio);
                        $ui->assign('date_end', $fechaFin);

                        $ui->assign('appointments', $appointments);

                        $item_sold = [];

                        $invoices_id = [];
                        foreach ($invoices as $ds) {
                            $invoices_id[] = $ds['id'];
                        }

                        if(count($invoices) != 0)
                        {
                            $all_invoice_items = InvoiceItem::where('itemcode', '!=', '')
                            ->whereIn('invoiceid', $invoices_id)
                            ->get()
                            ->groupBy('itemcode')
                            ->all();

                            $all_items = Item::select('id', 'name', 'item_number')
                            ->get()
                            ->keyBy('item_number')
                            ->all();

                            foreach ($all_invoice_items as $key => $value) {
                                $count = count($value);
                                $amount = 0;
                                $name = '';

                                foreach ($value as $item) {
                                    $amount += $item->amount * $item->qty;
                                    $owners = ORM::for_table('sys_items')->find($item->itemcode);
                                    $agente=$owners->name;
                                }

                                if (isset($all_items[$key])) {
                                    $name = $all_items[$key]->name;
                                }

                                $item_sold[] = [
                                    'name' => $agente,
                                    'sold_count' => $count,
                                    'total_amount' => $amount,
                                ];
                            }
                        }

                        $item_sold_circular = array_slice($item_sold, 0, 10);
                        $ui->assign('item_sold', $item_sold_circular);

                        $ui->assign('directorio', APP_DIRECTORIO);

                        view('welcome');
                        ib_close();
                    }

                $tasks = [];

                if (
                    isset($config['dashboard_widgets_tasks']) &&
                    $config['dashboard_widgets_tasks'] == 1
                ) {
                    $tasks = Task::orderBy('id', 'desc')
                    ->limit(5)
                    ->get();
                }

                $dashboard_section_0 = '';

                $tbal = ORM::for_table('sys_accounts')->sum('balance');

                $tbal = $tbal ? number_format($tbal, '2', '.', '') : 0;


                $ui->assign('tbal', $tbal);

                $balances = getBalances($user);

                $net_worth = $balances['net_worth'];

                $home_currency = $balances['home_currency'];

                if ($net_worth == '') {
                    $net_worth = 0;
                }
                $ui->assign('net_worth', $net_worth);
                $goal = $config['networth_goal'];
                $v_goal = number_format(
                    $goal,
                    2,
                    $config['dec_point'],
                    $config['thousands_sep']
                );
                if ($goal != '' && $goal != '0') {
                    $division = $net_worth / $goal;
                    $pg = $division * 100;
                    $pg = number_format($pg, 2, '.', '');
                } else {
                    $pg = '0';
                }
                $ui->assign('pg', $pg);
                $pgb = $pg <= 100 ? $pg : '100';
                $ui->assign('pgb', $pgb);
                if ($pgb < 49) {
                    $ui->assign('pgc', 'danger');
                } elseif ($pgb < 69) {
                    $ui->assign('pgc', 'warning');
                } else {
                    $ui->assign('pgc', 'success');
                }

                $first_day_month = date('Y-m-01');
                $mdate = date('Y-m-d');


                $transactions_all = new Transaction();



                if (has_access($user->roleid, 'transactions', 'all_data')) {
                    $all_data_access = true;



                    $mi = ORM::for_table('sys_transactions')
                    ->where('type', 'Income')
                    ->where_gte('date', $first_day_month)
                    ->where_lte('date', $mdate)
                    ->sum('cr');
                    if ($mi == '') {
                        $mi = '0.00';
                    }
                    $ui->assign('mi', $mi);
                    $me = ORM::for_table('sys_transactions')
                    ->where('type', 'Expense')
                    ->where_gte('date', $first_day_month)
                    ->where_lte('date', $mdate)
                    ->sum('dr');
                    if ($me == '') {
                        $me = '0.00';
                    }
                    $ui->assign('me', $me);
                    $m = ORM::for_table('sys_transactions')
                    ->where('type', 'Income')
                    ->where('date', $mdate)
                    ->sum('amount');
                    if ($m == '') {
                        $m = '0.00';
                    }
                    $ui->assign('ti', $m);
                    $m = ORM::for_table('sys_transactions')
                    ->where('type', 'Expense')
                    ->where('date', $mdate)
                    ->sum('amount');
                    if ($m == '') {
                        $m = '0.00';
                    }
                    $ui->assign('te', $m);

                    $customers_total = Contact::where(
                        'type',
                        'like',
                        '%Customer%'
                    )->count();

                    if ($customers_total == '') {
                        $customers_total = '0';
                    }

                    $ui->assign('customers_total', $customers_total);

                    $companies_total = ORM::for_table('sys_companies')->count();

                    if ($companies_total == '') {
                        $companies_total = '0';
                    }

                    $ui->assign('companies_total', $companies_total);

                    $leads_total = ORM::for_table('crm_leads')->count();

                    if ($leads_total == '') {
                        $leads_total = '0';
                    }

                    $ui->assign('leads_total', $leads_total);

                    $invoices = ORM::for_table('sys_invoices')
                    ->limit(5)
                    ->order_by_desc('id')
                    ->find_many();
                    $ui->assign('invoices', $invoices);

                    /* $d = ORM::for_table('sys_transactions')
                    ->where('type', 'Expense')
                    ->limit(5)
                    ->order_by_desc('id')
                    ->find_many();
                    $ui->assign('exp', $d); */

                    $d = ORM::for_table('sys_transactions')
                    ->where('type', 'Income')
                    ->limit(5)
                    ->order_by_desc('id')
                    ->find_many();
                    $ui->assign('inc', $d);

                    $total_income = Transaction::where('type', 'Income')->sum('amount');
                    $total_expense = Transaction::where('type', 'Expense')->sum(
                        'amount'
                    );
                    $total_invoice_paid = Invoice::where('status', 'Paid')->sum(
                        'total'
                    );

                    /* $expense_cats = TransactionCategory::where('type', 'Expense')
                    ->orderBy('total_amount', 'desc')
                    ->take(10)
                    ->get(); */

                    /* $expense_cats = ORM::get_db()->query( 
                        "SELECT sys_transactions.account, s_cats.name , sys_transactions.type, sum(sys_transactions.amount) AS 'total_amount' FROM 
                            sys_transactions
                        JOIN 
                        sys_cats AS s_cats 
                        ON 
                        s_cats.id=sys_transactions.cat_id
                        WHERE sys_transactions.type = 'Expense'
                        GROUP BY sys_transactions.cat_id
                        ORDER BY total_amount DESC 
                        LIMIT 10;

                     ")->fetchAll(PDO::FETCH_ASSOC); */

                    $all_invoice_items = InvoiceItem::where('itemcode', '!=', '')
                    ->get()
                    ->groupBy('itemcode')
                    ->all();

                    $all_items = Item::select('id', 'name', 'item_number')
                    ->get()
                    ->keyBy('item_number')
                    ->all();

                    foreach ($all_invoice_items as $key => $value) {
                        $count = count($value);
                        $amount = 0;
                        $name = '';
                        $total  =0;
                        foreach ($value as $item) {
                            $amount += $item->amount * $item->qty;
                            $total = $item->amount - $item->discount_amount; 
                            //$total = $total * $item->qty;
                            $total = $total + $item->total;
                            $owners = ORM::for_table('sys_items')->find($item->itemcode);
                            $agente=$owners->name;
                            
                        }

                        if (isset($all_items[$key])) {
                            $name = $all_items[$key]->name;
                        }

                        $item_sold[] = [
                            'name' => $agente,

                            'sold_count' => $count,
                            'total_amount' =>  $amount,
                            'total' =>  $total,
                        ];
                    }
                    $weekFromDate = Carbon\Carbon::now()
                    ->subDay()
                    ->startOfWeek()
                    ->toDateString();
                    $today_date = date('Y-m-d');
                    $weekly_total_invoice_amount = Invoice::whereBetween('date', [
                        $weekFromDate,
                        $today_date,
                    ])->sum('total');
                    $weekly_total_invoice_paid = Invoice::whereBetween('date', [
                        $weekFromDate,
                        $today_date,
                    ])
                    ->where('status', 'Paid')
                    ->sum('total');
                    $weekly_total_invoice_due = Invoice::whereBetween('date', [
                        $weekFromDate,
                        $today_date,
                    ])
                    ->where('status', 'Unpaid')
                    ->sum('total');
                    $monthFromDate = Carbon\Carbon::now()
                    ->subDay()
                    ->startOfMonth()
                    ->toDateString();
                    $monthly_total_invoice_amount = Invoice::whereBetween('date', [
                        $monthFromDate,
                        $today_date,
                    ])->sum('total');
                    $monthly_total_invoice_paid = Invoice::whereBetween('date', [
                        $monthFromDate,
                        $today_date,
                    ])
                    ->where('status', 'Paid')
                    ->sum('total');
                    $monthly_total_invoice_due = Invoice::whereBetween('date', [
                        $monthFromDate,
                        $today_date,
                    ])
                    ->where('status', 'Unpaid')
                    ->sum('total');
                    $accounts = $balances['banks'];
                    $currencies = $balances['currencies'];
                } else {

                    $transactions_all = $transactions_all->where('aid', $user->id);

                    $mi = ORM::for_table('sys_transactions')
                    ->where('type', 'Income')
                    ->where_gte('date', $first_day_month)
                    ->where_lte('date', $mdate)
                    ->where('aid', $user->id)
                    ->sum('cr');
                    if ($mi == '') {
                        $mi = '0.00';
                    }
                    $ui->assign('mi', $mi);
                    $me = ORM::for_table('sys_transactions')
                    ->where('type', 'Expense')
                    ->where_gte('date', $first_day_month)
                    ->where_lte('date', $mdate)
                    ->where('aid', $user->id)
                    ->sum('dr');
                    if ($me == '') {
                        $me = '0.00';
                    }
                    $ui->assign('me', $me);
                    $m = ORM::for_table('sys_transactions')
                    ->where('type', 'Income')
                    ->where('date', $mdate)
                    ->where('aid', $user->id)
                    ->sum('cr');
                    if ($m == '') {
                        $m = '0.00';
                    }
                    $ui->assign('ti', $m);
                    $m = ORM::for_table('sys_transactions')
                    ->where('type', 'Expense')
                    ->where('date', $mdate)
                    ->where('aid', $user->id)
                    ->sum('dr');
                    if ($m == '') {
                        $m = '0.00';
                    }
                    $ui->assign('te', $m);

                    $customers_total = ORM::for_table('crm_accounts')
                    ->where('o', $user->id)
                    ->count();

                    if ($customers_total == '') {
                        $customers_total = '0';
                    }

                    $ui->assign('customers_total', $customers_total);

                    $companies_total = ORM::for_table('sys_companies')
                    ->where('aid', $user->id)
                    ->count();

                    if ($companies_total == '') {
                        $companies_total = '0';
                    }

                    $ui->assign('companies_total', $companies_total);

                    $leads_total = ORM::for_table('crm_leads')
                    ->where('aid', $user->id)
                    ->count();

                    if ($leads_total == '') {
                        $leads_total = '0';
                    }

                    $ui->assign('leads_total', $leads_total);

                    $invoices = ORM::for_table('sys_invoices')
                    ->where('aid', $user->id)
                    ->limit(5)
                    ->order_by_desc('id')
                    ->find_many();
                    $ui->assign('invoices', $invoices);

                    /* $d = ORM::for_table('sys_transactions')
                    ->where('aid', $user->id)
                    ->where('type', 'Expense')
                    ->limit(5)
                    ->order_by_desc('id')
                    ->find_many();
                    $ui->assign('exp', $d); */

                    $d = ORM::for_table('sys_transactions')
                    ->where('aid', $user->id)
                    ->where('type', 'Income')
                    ->limit(5)
                    ->order_by_desc('id')
                    ->find_many();
                    $ui->assign('inc', $d);
                    $total_income = Transaction::where('type', 'Income')
                    ->where('aid', $user->id)
                    ->sum('amount');
                    $total_expense = Transaction::where('type', 'Expense')
                    ->where('aid', $user->id)
                    ->sum('amount');
                    $total_invoice_paid = Invoice::where('status', 'Paid')
                    ->where('aid', $user->id)
                    ->sum('total');

                    /* $expense_cats = TransactionCategory::where('type', 'Expense')
                    ->orderBy('total_amount', 'desc')
                    ->take(10)
                    ->get(); */

                    /* $expense_cats = ORM::get_db()->query( 
                       "SELECT sys_transactions.account, s_cats.name , sys_transactions.type, sum(sys_transactions.amount) AS 'total_amount' FROM 
                            sys_transactions
                        JOIN 
                        sys_cats AS s_cats 
                        ON 
                        s_cats.id=sys_transactions.cat_id
                        WHERE sys_transactions.type = 'Expense'
                        GROUP BY sys_transactions.cat_id
                        ORDER BY total_amount DESC 
                        LIMIT 10;

                    ")->fetchAll(PDO::FETCH_ASSOC); */


                    $item_sold = Item::select('name', 'sold_count', 'total_amount')
                    ->orderBy('sold_count', 'desc')
                    ->take(10)
                    ->get();

                    $weekFromDate = Carbon\Carbon::now()
                    ->subDay()
                    ->startOfWeek()
                    ->toDateString();

                    $today_date = date('Y-m-d');

                    $weekly_total_invoice_amount = Invoice::whereBetween('date', [
                        $weekFromDate,
                        $today_date,
                    ])
                    ->where('aid', $user->id)
                    ->sum('total');
                    $weekly_total_invoice_paid = Invoice::whereBetween('date', [
                        $weekFromDate,
                        $today_date,
                    ])
                    ->where('aid', $user->id)
                    ->where('status', 'Paid')
                    ->sum('total');
                    $weekly_total_invoice_due = Invoice::whereBetween('date', [
                        $weekFromDate,
                        $today_date,
                    ])
                    ->where('aid', $user->id)
                    ->where('status', 'Unpaid')
                    ->sum('total');
                    $monthFromDate = Carbon\Carbon::now()
                    ->subDay()
                    ->startOfMonth()
                    ->toDateString();
                    $monthly_total_invoice_amount = Invoice::whereBetween('date', [
                        $monthFromDate,
                        $today_date,
                    ])
                    ->where('aid', $user->id)
                    ->sum('total');
                    $monthly_total_invoice_paid = Invoice::whereBetween('date', [
                        $monthFromDate,
                        $today_date,
                    ])
                    ->where('aid', $user->id)
                    ->where('status', 'Paid')
                    ->sum('total');
                    $monthly_total_invoice_due = Invoice::whereBetween('date', [
                        $monthFromDate,
                        $today_date,
                    ])
                    ->where('aid', $user->id)
                    ->where('status', 'Unpaid')
                    ->sum('total');
                    $accounts = Account::take(5)->get();
                    $currencies = Currency::all();
                }

                $total_income = 0;
                $total_expense = 0;

                $income_today = 0;
                $expense_today = 0;

                $income_this_month = 0;
                $expense_this_month = 0;

                $today = date('Y-m-d');

                $month_start_date = date('Y-m-01');
                $month_end_date = date('Y-m-t');

                $transactions_all = $transactions_all->get();

                foreach ($transactions_all as $transaction)
                {
                    if($transaction->type === 'Income')
                    {
                        $total_income += $transaction->amount*$transaction->currency_rate;
                    }
                    elseif($transaction->type === 'Expense')
                    {
                        $total_expense += $transaction->amount*$transaction->currency_rate;
                    }

                    if($transaction->date === $today)
                    {
                        if($transaction->type === 'Income')
                        {
                            $income_today += $transaction->amount*$transaction->currency_rate;
                        }
                        elseif($transaction->type === 'Expense')
                        {
                            $expense_today += $transaction->amount*$transaction->currency_rate;
                        }
                    }

                    if($transaction->date >= $month_start_date && $transaction->date <= $month_end_date)
                    {
                        if($transaction->type === 'Income')
                        {
                            $income_this_month += $transaction->amount*$transaction->currency_rate;
                        }
                        elseif($transaction->type === 'Expense')
                        {
                            $expense_this_month += $transaction->amount*$transaction->currency_rate;
                        }
                    }

                }


                $recent_projects = Project::orderBy('id', 'desc')
                ->limit(5)
                ->get();
                $recent_customers = Contact::orderBy('id', 'desc')
                ->limit(5)
                ->get();
                $total_projects = Project::count();


                //print_r(json_encode($expense_cats));exit;

                view('dashboard_canvas', [
                    //'expense_cats' => $expense_cats,
                    //'expense_cats' => [],
                    'total_income' => $balances['total_income'] ?? $total_income,
                    'total_expense' => $balances['total_expense'] ?? $total_expense,
                    'total_invoice_paid' => $total_invoice_paid,
                    'item_sold' => $item_sold,
                    'weekly_total_invoice_amount' => $weekly_total_invoice_amount,
                    'weekly_total_invoice_paid' => $weekly_total_invoice_paid,
                    'weekly_total_invoice_due' => $weekly_total_invoice_due,
                    'monthly_total_invoice_amount' => $monthly_total_invoice_amount,
                    'monthly_total_invoice_paid' => $monthly_total_invoice_paid,
                    'monthly_total_invoice_due' => $monthly_total_invoice_due,
                    'accounts' => $accounts,
                    'currencies' => $currencies,
                    'home_currency' => $home_currency,
                    'all_data_access' => $all_data_access,
                    'balances' => $balances,
                    'all_items' => $all_items,
                    'tasks' => $tasks,
                    'recent_projects' => $recent_projects,
                    'recent_customers' => $recent_customers,
                    'total_projects' => $total_projects,
                    'income_today' => $income_today,
                    'expense_today' => $expense_today,
                    'income_this_month' => $income_this_month,
                    'expense_this_month' => $expense_this_month,
                    'directorio' => APP_DIRECTORIO,
                ]);

        break;

        case 'filtro-fecha-admin':             
                
            
            //$monthFromDate = Carbon\Carbon::now()
            $json = file_get_contents('php://input');

            // Decodifica el JSON a un array asociativo
            $informacion_front = json_decode($json, true);
    
            $startDate = $informacion_front['startDate'];
            $endDate = $informacion_front['endDate'];

            if(empty($startDate) == true || empty($endDate) == true )
            {
                $response = array(
                    "type" => "error",
                    "message" => "¡Incorrect date!",
                );
                print_r(json_encode($response)); exit;
            }

            //Sales
            $item_sold = [];

            $all_invoice_items = InvoiceItem::where('itemcode', '!=', '')
            ->whereBetween('created_at', [$startDate . " 00:00:01", $endDate . " 23:59:59"])
            ->get()
            ->groupBy('itemcode')
            ->all();

            $all_items = Item::select('id', 'name', 'item_number')
            ->get()
            ->keyBy('item_number')
            ->all();

            $total_sumar = 0;

            foreach ($all_invoice_items as $key => $value) {
                $count = count($value);
                $amount = 0;
                $name = '';

                $total = 0;
                 

                foreach ($value as $item) {
                    $amount += $item->amount * $item->qty;
                    //$total = $item->amount - $item->discount_amount; 
                    $total = $total + $item->total;
                    
                    $owners = ORM::for_table('sys_items')->find($item->itemcode);
                    $agente=$owners->name;
                }

                $total_sumar = $total_sumar + $total;

                if (isset($all_items[$key])) {
                    $name = $all_items[$key]->name;
                }

                $item_sold[] = [
                    'name' => $agente,
                    'sold_count' => $count,
                    'total_amount' => $amount,
                    'total' => formatCurrency($total, $config['home_currency']),
                ];
            }
            //Fin de Sales

            //Recent Invoices
            $invoices = Invoice::whereBetween('created_at', [$startDate . " 00:00:01", $endDate . " 23:59:59"])
            ->get()
            ->all();

            //Fin Recent Invoices
            
            $transacciones_income = [];

            //query basada este codigo
            //SELECT SUM(total) AS 'total_amount', SUM(credit) AS 'total_pain', SUM(total-credit) AS 'total_amout_due' FROM `sys_invoices` WHERE date BETWEEN '2024-07-01' and '2024-07-31' AND type="Invoice" AND aid != 0 GROUP BY `aid` asc

            $all_invoice_items = Invoice::where('type', 'Invoice')
            ->where('aid', "!=" , '0')
            ->whereBetween('datepaid', [$startDate ." 00:00:01" , $endDate . " 23:59:59" ])
            ->orderBy('aid', 'asc')
            ->get()
            ->groupBy('aid')
            ->all();

            $fecha_inicio_con = $startDate ." 00:00:01";
            $fecha_fin_con = $endDate ." 23:59:59";

            
            $mysqli = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
            $mysqli->set_charset("utf8");

            

            $data_template_invoices = $mysqli->query("SELECT 
                                                        SUM(STra.amount) AS total_pain,
                                                        SU.fullname

                                                     FROM `sys_transactions` AS STra 
                                                     LEFT JOIN `sys_users` AS SU ON STra.staff_id_pago = SU.id
                                                     WHERE 
                                                     STra.updated_at between '$fecha_inicio_con' and '$fecha_fin_con' 
                                                     AND STra.`type`='Income' AND STra.staff_id_pago is not null
                                                      GROUP BY STra.staff_id_pago")->fetch_all(MYSQLI_ASSOC) ;

            //echo json_encode($data_template_invoices); exit;
                                                     
 
            //$invoices = Invoice::whereBetween('date', [$fechaInicio, $fechaFin]);

 
            /* foreach ($all_invoice_items as $key => $value) {
                $count = count($value); //total de facturas
                $total_amount    = 0; //total de toda las factura
                $total_pain      = 0; //total de todo lo que me pagan de la factura
                $total_amout_due = 0; //total de todo lo que me deben
 
                //$total = 0;

                $id_usuario = 0;

                foreach ($value as $item) {

                    $total_amount += $item->total;
                    $total_pain += $item->credit;
                    $total_amout_due += $item->total - $item->credit;
                    
                    $id_usuario = $item->aid;

                }

 
                $owners = ORM::for_table('sys_users')->find($id_usuario);
                $fullname=$owners->fullname;

                $empleados_facturas[] = [
                    'name'              => $fullname,
                    'id_usuario'        => $id_usuario,
                    'cantidad_facturas' => $count,
                    'total_amount'      => $total_amount,
                    'total_pain'        => $total_pain,
                    'total_amout_due'   => $total_amout_due,
                    //'total'             => formatCurrency($total * $count, $config['home_currency']),
                ];
            } */
            //Fin de employee

            $empleados_facturas_html = '';

            $invoices_employees_cantidad = 0;
            $invoices_employees_amount = 0;
            $invoices_employees_pain = 0;
            $invoices_employees_amount_due = 0;

            foreach ($data_template_invoices as $ds) {

                //$fullname   +=  $ds['fullname'];
                //$invoices_employees_amount     +=  $ds['total_amount'];
                $invoices_employees_pain       +=  $ds['total_pain'];
                //$invoices_employees_amount_due +=  $ds['total_amout_due'];

                $empleados_facturas_html .= '<tr  >';
                $empleados_facturas_html .= '<td class="h6"><strong>' . $ds['fullname'] . '</strong> <br></td>';
                //$empleados_facturas_html .= '<td class="h6">' . $ds['cantidad_facturas'] . '</td>';
                //$empleados_facturas_html .= '<td class="h6">' . formatCurrency($ds['total_amount'], $ds['currency_iso_code']) . '</td>';
                $empleados_facturas_html .= '<td class="text-success h6"><strong>' . formatCurrency($ds['total_pain'], $ds['currency_iso_code']) . '</strong></td>';
                //$empleados_facturas_html .= '<td class="text-danger h6"><strong>' . formatCurrency($ds['total_amout_due'], $ds['currency_iso_code']) . '</strong></td>';
                $empleados_facturas_html .= '</tr>';
            }

            $empleados_facturas_html .= '<tr >';
            $empleados_facturas_html .= '<td class="h6"><strong>' . "Total:" . '</strong> <br></td>';
            //$empleados_facturas_html .= '<td class="h6">' . $invoices_employees_cantidad . '</td>';
            //$empleados_facturas_html .= '<td class="h6">' . formatCurrency($invoices_employees_amount, $ds['currency_iso_code']) . '</td>';
            $empleados_facturas_html .= '<td class="text-success h6"><strong>' . formatCurrency($invoices_employees_pain, $ds['currency_iso_code']) . '</strong></td>';
            //$empleados_facturas_html .= '<td class="text-danger h6"><strong>' . formatCurrency($invoices_employees_amount_due, $ds['currency_iso_code']) . '</strong></td>';
            $empleados_facturas_html .= '</tr>';

 

            //Recent Invoices Porcentaje
            if (has_access($user->roleid, 'transactions', 'all_data')) {
                $paid = ORM::for_table('sys_invoices')
                ->where_raw('created_at BETWEEN ? AND ?', [$startDate . " 00:00:01", $endDate . " 23:59:59"])
                ->where('status', 'Paid')
                ->count();
                $unpaid = ORM::for_table('sys_invoices')
                ->where_raw('created_at BETWEEN ? AND ?', [$startDate . " 00:00:01", $endDate . " 23:59:59"])
                ->where('status', 'Unpaid')
                ->count();
                $partially_paid = ORM::for_table('sys_invoices')
                ->where_raw('created_at BETWEEN ? AND ?', [$startDate . " 00:00:01", $endDate . " 23:59:59"])
                ->where('status', 'Partially Paid')
                ->count();
                $modify_discount = ORM::for_table('sys_invoices')
                ->where_raw('created_at BETWEEN ? AND ?', [$startDate . " 00:00:01", $endDate . " 23:59:59"])
                ->where('status', 'Modify Discount')
                ->count();
                $pending_approval = ORM::for_table('sys_invoices')
                ->where_raw('created_at BETWEEN ? AND ?', [$startDate . " 00:00:01", $endDate . " 23:59:59"])
                ->where('status', 'Pending Approval')
                ->count();
                $reject = ORM::for_table('sys_invoices')
                ->where_raw('created_at BETWEEN ? AND ?', [$startDate . " 00:00:01", $endDate . " 23:59:59"])
                ->where('status', 'Reject')
                ->count();

                $total_expense = Transaction::where('type', 'Expense')
                ->whereBetween('date', [$startDate, $endDate])
                ->sum(
                    'amount'
                );

                $transacciones_income = ORM::for_table('sys_transactions')
                ->where_raw('date BETWEEN ? AND ?', [$startDate, $endDate])
                ->where('type', 'Income')
                ->order_by_desc('id')
                ->find_many();
                 

            } else {
                $paid = ORM::for_table('sys_invoices')
                ->where_raw('created_at BETWEEN ? AND ?', [$startDate . " 00:00:01", $endDate . " 23:59:59"])
                ->where('status', 'Paid')
                ->where('aid', $user->id)
                ->count();
                $unpaid = ORM::for_table('sys_invoices')
                ->where_raw('created_at BETWEEN ? AND ?', [$startDate . " 00:00:01", $endDate . " 23:59:59"])
                ->where('status', 'Unpaid')
                ->where('aid', $user->id)
                ->count();
                $partially_paid = ORM::for_table('sys_invoices')
                ->where_raw('created_at BETWEEN ? AND ?', [$startDate . " 00:00:01", $endDate . " 23:59:59"])
                ->where('status', 'Partially Paid')
                ->where('aid', $user->id)
                ->count();
                $modify_discount = ORM::for_table('sys_invoices')
                ->where_raw('created_at BETWEEN ? AND ?', [$startDate . " 00:00:01", $endDate . " 23:59:59"])
                ->where('status', 'Modify Discount')
                ->where('aid', $user->id)
                ->count();
                $pending_approval = ORM::for_table('sys_invoices')
                ->where_raw('created_at BETWEEN ? AND ?', [$startDate . " 00:00:01", $endDate . " 23:59:59"])
                ->where('status', 'Pending Approval')
                ->where('aid', $user->id)
                ->count();
                $reject = ORM::for_table('sys_invoices')
                ->where_raw('created_at BETWEEN ? AND ?', [$startDate . " 00:00:01", $endDate . " 23:59:59"])
                ->where('status', 'Reject')
                ->where('aid', $user->id)
                ->count();

                $total_expense = Transaction::where('type', 'Expense')
                ->whereBetween('date', [$startDate, $endDate])
                ->where('aid', $user->id)
                ->sum('amount');

                $transacciones_income = ORM::for_table('sys_transactions')
                ->where_raw('date BETWEEN ? AND ?', [$startDate, $endDate])
                ->where('aid', $user->id)
                ->where('type', 'Income')
                ->order_by_desc('id')
                ->find_many();

            }
    
            $arr = [
                'Paid' => $paid,
                'Unpaid' => $unpaid,
                'Partially_Paid' => $partially_paid,
                'Modify_Discount' => $modify_discount,
                'Pending_Approval' => $pending_approval,
                'Reject' => $reject,
            ];
    
            $p = Misc::array_percentage($arr);
            //FIN Recent Invoices Porcentaje

            //recent_customers
            $recent_customers = Contact::orderBy('id', 'asc')
            ->whereBetween('created_at', [$startDate . " 00:00:01", $endDate . " 23:59:59"])
            ->get();
            //fin recent_customers

            
            $item_sold_circular = array_slice($item_sold, 0, 10);


            $recent_clients_tabla = '';

            foreach ($recent_customers as $index => $recent_customer) {
                $iteration = $index + 1; // La iteración actual
                $recent_clients_tabla .= '<tr>';
                $recent_clients_tabla .= '<td data-order="' . $iteration . '">';
                $recent_clients_tabla .= '<a href="' . U . 'contacts/view/' . $recent_customer->id . '">' . sp_get_contact_image($recent_customer) . '</a>';
                $recent_clients_tabla .= '</td>';
                $recent_clients_tabla .= '<td>';
                $recent_clients_tabla .= '<a class="h6" href="' . $base_url . 'contacts/view/' . $recent_customer->id . '">' . htmlspecialchars($recent_customer->account) . '</a><br>';
                $recent_clients_tabla .= htmlspecialchars($recent_customer->email);
                $recent_clients_tabla .= '</td>';
                $recent_clients_tabla .= '<td>';
                if (!empty($recent_customer->created_at)) {
                    $recent_clients_tabla .= date($config['df'], strtotime($recent_customer->created_at));
                }
                $recent_clients_tabla .= '</td>';
                $recent_clients_tabla .= '</tr>';
            }   

            $invoices_table_html = '';

            $Amount_recent_invoices =  0;
            $Pain_recent_invoices =  0;
            $Amount_Due_recent_invoices =  0;

            foreach ($invoices as $ds) {

                $Amount_recent_invoices     +=  $ds['total'];
                $Pain_recent_invoices       +=  $ds['credit'];
                $Amount_Due_recent_invoices +=  $ds['total'] - $ds['credit'];
 

                $invoices_table_html .= '<tr class="cursor-pointer clickable-row" data-id="' . htmlspecialchars($ds['id']) . '">';
                $invoices_table_html .= '<td class="text-info h6">';
                $invoices_table_html .= '<strong>';
                $invoices_table_html .= htmlspecialchars($ds['invoicenum']);
                if ($ds['cn'] !== '') {
                    $invoices_table_html .= ' ' . htmlspecialchars($ds['cn']);
                } else {
                    $invoices_table_html .= ' ' . htmlspecialchars($ds['id']);
                }
                $invoices_table_html .= '</strong>';
                $invoices_table_html .= '</td>';
                $invoices_table_html .= '<td class="h6">';
                $invoices_table_html .= '<strong>' . htmlspecialchars($ds['account']) . '</strong><br>';
                $invoices_table_html .= '</td>';

                $invoices_table_html .= '<td class="h6">' . formatCurrency($ds['total'], $ds['currency_iso_code']) . '</td>'; // esta es la info buena
                $invoices_table_html .= '<td class="h6 text-success">' . formatCurrency($ds['credit'], $ds['currency_iso_code']) . '</td>'; // esta es la info buena
                $invoices_table_html .= '<td class="h6 text-danger">' . formatCurrency($ds['total'] - $ds['credit'], $ds['currency_iso_code']) . '</td>'; // esta es la info buena


                $invoices_table_html .= '<td class="h6">';
                if (!empty($ds['date'])) {
                    $invoices_table_html .= date($config['df'], strtotime($ds['date']));
                } else {
                    $invoices_table_html .= '--';
                }
                $invoices_table_html .= '</td>';
                $invoices_table_html .= '<td class="h6">';
                if (!empty($ds['duedate'])) {
                    $invoices_table_html .= date($config['df'], strtotime($ds['duedate']));
                } else {
                    $invoices_table_html .= '--';
                }
                $invoices_table_html .= '</td>';
                $invoices_table_html .= '<td class="h6">';
                if ($ds['status'] == 'Unpaid') {
                    $invoices_table_html .= '<span class="badge badge-outline badge-outline-danger">' . ib_lan_get_line($ds['status']) . '</span>';
                } else {
                    $invoices_table_html .= '<span class="badge badge-outline badge-outline-success">' . ib_lan_get_line($ds['status']) . '</span>';
                }
                $invoices_table_html .= '</td>';
                $invoices_table_html .= '</tr>';
            }

                $invoices_table_html .= '<tr>';

                $invoices_table_html .= '<td class="h6">';
                $invoices_table_html .= '<strong>Total:</strong>';
                $invoices_table_html .= '</td>';

                $invoices_table_html .= '<td class="h6">';
                $invoices_table_html .= '</td>';

                $invoices_table_html .= '<td style="font-weight: 600">' . formatCurrency($Amount_recent_invoices, $ds['currency_iso_code']) . '</td>'; // esta es la info buena
                $invoices_table_html .= '<td style="font-weight: 600">' . formatCurrency($Pain_recent_invoices, $ds['currency_iso_code']) . '</td>'; // esta es la info buena
                $invoices_table_html .= '<td style="font-weight: 600">' . formatCurrency($Amount_Due_recent_invoices, $ds['currency_iso_code']) . '</td>'; // esta es la info buena

                $invoices_table_html .= '<td class="h6"></td>';
                $invoices_table_html .= '<td class="h6"></td>';
                $invoices_table_html .= '<td class="h6"></td>';
                 
                $invoices_table_html .= '</tr>';

            $expense_html = "";

            $transactions_all = new Transaction();
            $transactions_all_today = new Transaction();
            $transactions_all_month = new Transaction();
             
            if (has_access($user->roleid, 'transactions', 'all_data')) {
               

                /* $exp = ORM::for_table('sys_transactions')
                ->where_raw('date BETWEEN ? AND ?', [$startDate  , $endDate  ])
                ->where('type', 'Expense')
                ->order_by_desc('id')
                ->find_many();

                foreach ($exp as $exps) {
                    $expense_html .= '<tr>';
                    $expense_html .= '<td class="text-info h6">';
                    if (!empty($exps['date'])) {
                        $expense_html .= date($config['df'], strtotime($exps['date']));
                    } else {
                        $expense_html .= '--';
                    }
                    $expense_html .= '</td>';
                    $expense_html .= '<td><a href="' . U . 'transactions/manage/' . $exps['id'] . '/"><strong>' . htmlspecialchars($exps['description']) . '</strong></a></td>';
                    $expense_html .= '<td class="text-end text-danger amount h6">' . formatCurrency($exps['amount'], $config['home_currency']) . '</td>';
                    $expense_html .= '</tr>';
                } */


            } else {

                $transactions_all = $transactions_all->where('aid', $user->id);
                $transactions_all_today = $transactions_all_today->where('aid', $user->id);
                $transactions_all_month = $transactions_all_month->where('aid', $user->id);
             
                /* $exp = ORM::for_table('sys_transactions')
                ->where_raw('date BETWEEN ? AND ?', [$startDate , $endDate  ])
                ->where('aid', $user->id)
                ->where('type', 'Expense')
                ->order_by_desc('id')
                ->find_many();

                foreach ($exp as $exps) {
                    $expense_html .= '<tr>';
                    $expense_html .= '<td class="text-info h6">';
                    if (!empty($exps['date'])) {
                        $expense_html .= date($config['df'], strtotime($exps['date']));
                    } else {
                        $expense_html .= '--';
                    }
                    $expense_html .= '</td>';
                    $expense_html .= '<td><a href="' . U . 'transactions/manage/' . $exps['id'] . '/"><strong>' . htmlspecialchars($exps['description']) . '</strong></a></td>';
                    $expense_html .= '<td class="text-end text-danger amount h6">' . formatCurrency($exps['amount'], $config['home_currency']) . '</td>';
                    $expense_html .= '</tr>';
                } */

      
            }

            //account balance
            $balances = getBalancesByFecha($user, $startDate, $endDate);

            $net_worth = $balances['net_worth'];

            $home_currency = $balances['home_currency'];

            if ($net_worth == '') {
                $net_worth = 0;
            }

            $goal = $config['networth_goal'];
            $v_goal = number_format(
                $goal,
                2,
                $config['dec_point'],
                $config['thousands_sep']
            );

            $pg = '0';
            if ($goal != '' && $goal != '0') {
                $division = $net_worth / $goal;
                $pg = $division * 100;
                $pg = number_format($pg, 2, '.', '');
            } else {
                $pg = '0';
            }

            $pgb = $pg <= 100 ? $pg : '100';
            $pgc = "";
            if ($pgb < 49) {
                $pgc = "danger";
            } elseif ($pgb < 69) {
                $pgc = "warning";
            } else {
                $pgc = "success";
            }

            $balances_html = '';
            foreach ($balances['banks'] as $bank) {
                $balances_html .= '<tr>';
                $balances_html .= '<td class="text-info h6"><strong>' . htmlspecialchars($bank->account) . '</strong></td>';
                $balances_html .= '<td class="text-end h6">';
                if (isset($balances['balances'][$bank->id])) {
                    $balances_html .= formatCurrency($balances['balances'][$bank->id], $balances['home_currency']->iso_code);
                }
                $balances_html .= '</td>';
                $balances_html .= '</tr>';
            }

            $balances_data = array(
                "net_worth" => formatCurrency($net_worth,$config['home_currency']),
                "pg" => $pg,
                "pgb" => $pgb,
                "pgc" => $pgc,
                "balances_html" => $balances_html,

            );
            //fin de account balance

            //income_vs_expense
            $income_vs_expense = Dashboard::dataIncExpDByDate('dd', $startDate);
            //fin income_vs_expense

            //summary
            $total_income = 0;
            $total_expense = 0;

            $income_today = 0;
            $expense_today = 0;

            $income_this_month = 0;
            $expense_this_month = 0;

            //strtotime("2024-06-19")
            $today = date('Y-m-d');

            $month_start_date = date('Y-m-01',strtotime($startDate));
            $month_end_date = date('Y-m-t',strtotime($startDate));

            //$transactions_all = $transactions_all->whereBetween('date', [$startDate, $endDate])->get();
            $transactions_all = $transactions_all->get();
            $transactions_all_today = $transactions_all_today->where('date', $today)->get();
            $transactions_all_month = $transactions_all_month->whereBetween('date', [$month_start_date, $month_end_date])->get();
                        
            foreach ($transactions_all as $transaction)
            {
                if($transaction->type === 'Income')
                {
                    $total_income += $transaction->amount*$transaction->currency_rate;
                }
                elseif($transaction->type === 'Expense')
                {
                    $total_expense += $transaction->amount*$transaction->currency_rate;
                }

            }
            
            //for today
            foreach ($transactions_all_today as $transaction)
            {
                if($transaction->type === 'Income')
                {
                    $income_today += $transaction->amount*$transaction->currency_rate;
                }
                elseif($transaction->type === 'Expense')
                {
                    $expense_today += $transaction->amount*$transaction->currency_rate;
                }
            }

            //for para el mes
            foreach ($transactions_all_month as $transaction)
            {
                if($transaction->type === 'Income')
                {
                    $income_this_month += $transaction->amount*$transaction->currency_rate;
                }
                elseif($transaction->type === 'Expense')
                {
                    $expense_this_month += $transaction->amount*$transaction->currency_rate;
                }

            }

            //$grafica_summary = Dashboard::dataLastTwelveMonthsIncExp();
            $grafica_summary = Dashboard::dataLastTwelveMonthsIncExpByFecha($startDate);
              
            $info_summary = array(
                //total
                'total_income' =>formatCurrency($total_income,$config['home_currency']),
                'total_expense' => formatCurrency($total_expense, $config['home_currency']),
                //dia
                'income_today' => formatCurrency($income_today,$config['home_currency']),
                'expense_today' => formatCurrency($expense_today,$config['home_currency']),
                //mes
                'income_this_month' => formatCurrency($income_this_month,$config['home_currency']),
                'expense_this_month' => formatCurrency($expense_this_month,$config['home_currency']),
                //graficas
                'Expense' => $grafica_summary["Expense"] ?? [],
                'Income' => $grafica_summary["Income"] ?? [],
                'Months' => $grafica_summary["Months"] ?? [],
                'xd' => $grafica_summary["xd"] ?? [],


            );             

            //FIN summary

            //Last Income
            $last_income_html = '';
            foreach ($transacciones_income as $incs) {
                $last_income_html .= '<tr>';
                $last_income_html .= '<td class="h6 text-info">';
                if (!empty($incs->date)) {
                    $last_income_html .= date($config['df'], strtotime($incs->date));
                } else {
                    $last_income_html .= '--';
                }
                $last_income_html .= '</td>';
                $last_income_html .= '<td><a href="' . U . 'transactions/manage/' . $incs->id . '/"><strong>' . htmlspecialchars($incs->description) . '</strong></a></td>';
                $last_income_html .= '<td class="text-end text-success amount h6">' . formatCurrency($incs->amount, $config['home_currency']) . '</td>';
                $last_income_html .= '</tr>';
            }
            //FIN Last Income

            //
            /* $expense_cats = TransactionCategory::where('type', 'Expense')
            ->orderBy('total_amount', 'desc')
            ->take(10)
            ->get(); */
            /* $expense_cats = ORM::get_db()->query( 
                "SELECT sys_transactions.account, s_cats.name , sys_transactions.type, sum(sys_transactions.amount) AS 'total_amount' FROM 
                     sys_transactions
                 JOIN 
                 sys_cats AS s_cats 
                 ON 
                 s_cats.id=sys_transactions.cat_id
                 WHERE sys_transactions.type = 'Expense' AND date BETWEEN ' $startDate' AND '$endDate'
                 GROUP BY sys_transactions.cat_id
                 ORDER BY total_amount DESC 
                 LIMIT 10;

             ")->fetchAll(PDO::FETCH_ASSOC); */
            //

 
            
            $response = array(
                "type"                       => "success",
                "message"                    => "¡Information Saved Successfully!",
                "startDate"                  => $startDate,
                "endDate"                    => $endDate,
                "info_summary"               => $info_summary, // la ocupo 
                //"transactions_all"         => $transactions_all,//borrar
                "income_vs_expense"          => $income_vs_expense, // lo ocupo
                "balances_data"              => $balances_data,//lo uso/ocupo
                //"balances"                 => $balances, //no lo ocupo
                "item_sold"                  => $item_sold,// ocupado
                "item_sold_circular"         => $item_sold_circular, // ocupado
                //"invoices"                 => $invoices, no lo ocupo
                "porcentajes"                => $p,//lo uso/ocupo
                "recent_customers_html"      => $recent_clients_tabla,// ocupado
                "invoices_html"              => $invoices_table_html,// ocupado
                "expense_html"               => $expense_html,// ocupado
                "last_income_html"           => $last_income_html,// ocupado
                //"expense_cats"               => $expense_cats ?? [],// ocupado
                "total_suma_sales"           => formatCurrency($total_sumar, $config['home_currency']) ?? "$0.00",// ocupado
                "Amount_recent_invoices"     => formatCurrency($Amount_recent_invoices, $config['home_currency']) ?? "$0.00",// ocupado
                "Pain_recent_invoices"       => formatCurrency($Pain_recent_invoices, $config['home_currency']) ?? "$0.00",// ocupado
                "Amount_Due_recent_invoices" => formatCurrency($Amount_Due_recent_invoices, $config['home_currency']) ?? "$0.00",// ocupado
                "empleados_facturas_html"    => $empleados_facturas_html,// ocupado
            );
            print_r(json_encode($response)); exit;
             
             
        break;

        case 'filtro-fecha-cliente':
            //$monthFromDate = Carbon\Carbon::now()
            $json = file_get_contents('php://input');

            // Decodifica el JSON a un array asociativo
            $informacion_front = json_decode($json, true);
    
            $startDate = $informacion_front['startDate'];
            $endDate = $informacion_front['endDate'];

            if(empty($startDate) == true || empty($endDate) == true )
            {
                $response = array(
                    "type" => "error",
                    "message" => "¡Incorrect date!",
                );
                print_r(json_encode($response)); exit;
            }

            $invoices = Invoice::whereBetween('date', [$startDate, $endDate]);

            $invoices = $invoices->where('aid', $user->id)->get();

            $appointments = ORM::for_table('app_appointments')
            ->where('admin_id', $user->id)
            ->limit(5)
            ->order_by_desc('id')
            ->find_many();

            $invoices_html = '';
            $total = 0;
            $mon = '';

            $invoices_id = [];

            foreach ($invoices as $ds) {
                // Acumular el total y establecer la moneda
                $total += $ds['credit'];
                $mon = $ds['currency_iso_code'];

                $invoices_id[] = $ds['id'];
            
                // Iniciar una fila de tabla
                $invoices_html .= '<tr class="cursor-pointer clickable-row" data-id="' . htmlspecialchars($ds['id']) . '">';
                
                // Número de factura y condición con enlace
                $invoices_html .= '<td class="text-info h6"><a href="' . htmlspecialchars(U . 'invoices/view/' . $ds['id'] . '/') . '" class="text-info"><strong>';
                $invoices_html .= htmlspecialchars($ds['invoicenum']);
                if ($ds['cn'] != '') {
                    $invoices_html .= ' ' . htmlspecialchars($ds['cn']);
                } else {
                    $invoices_html .= ' ' . htmlspecialchars($ds['id']);
                }
                $invoices_html .= '</strong></a></td>';
                
                // Cuenta
                $invoices_html .= '<td class="h6"><strong>' . htmlspecialchars($ds['account']) . '</strong> <br></td>';
                
                // Total formateado
                $invoices_html .= '<td class="h6">' . formatCurrency($ds['credit'], $ds['currency_iso_code']) . '</td>';

                //title
                $invoices_html .= '<td class="h6">' . $ds['title'] . '</td>';
                
                // Fecha
                $invoices_html .= '<td class="h6">';
                if (!empty($ds['date'])) {
                    $invoices_html .= date($config['df'], strtotime($ds['date']));
                } else {
                    $invoices_html .= '--';
                }
                $invoices_html .= '</td>';
                
                // Fecha de vencimiento
                $invoices_html .= '<td class="h6">';
                if (!empty($ds['duedate'])) {
                    $invoices_html .= date($config['df'], strtotime($ds['duedate']));
                } else {
                    $invoices_html .= '--';
                }
                $invoices_html .= '</td>';
                
                // Estado
                $invoices_html .= '<td class="h6">';
                if ($ds['status'] == 'Unpaid') {
                    $invoices_html .= '<span class="badge badge-outline badge-outline-danger">' . ib_lan_get_line($ds['status']) . '</span>';
                } else {
                    $invoices_html .= '<span class="badge badge-outline badge-outline-success">' . ib_lan_get_line($ds['status']) . '</span>';
                }
                $invoices_html .= '</td>';
                
                // Cerrar la fila de tabla
                $invoices_html .= '</tr>';
            }

            //Sales
            $item_sold = [];

            if(count($invoices) != 0)
            {
                $all_invoice_items = InvoiceItem::where('itemcode', '!=', '')
                ->whereBetween('created_at', [$startDate . " 00:00:01", $endDate . " 23:59:59"])
                ->whereIn('invoiceid', $invoices_id)
                ->get()
                ->groupBy('itemcode')
                ->all();

                $all_items = Item::select('id', 'name', 'item_number')
                ->get()
                ->keyBy('item_number')
                ->all();

                foreach ($all_invoice_items as $key => $value) {
                    $count = count($value);
                    $amount = 0;
                    $name = '';

                    foreach ($value as $item) {
                        $amount += $item->amount * $item->qty;
                        $owners = ORM::for_table('sys_items')->find($item->itemcode);
                        $agente=$owners->name;
                    }

                    if (isset($all_items[$key])) {
                        $name = $all_items[$key]->name;
                    }

                    $item_sold[] = [
                        'name' => $agente,
                        'sold_count' => $count,
                        'total_amount' => $amount,
                    ];
                }
            }
            

            $response = array(
                "type"                    => "success",
                "message"                 => "¡Information Saved Successfully!",
                "startDate"               => $startDate,
                "endDate"                 => $endDate,
                //"invoices"                => $invoices,
                "invoices_html"           => $invoices_html,
                "total_invoices"          => formatCurrency($total,$mon),
                "appointments"            => $appointments,
                "item_sold_circular"      => $item_sold_circular = array_slice($item_sold, 0, 10),
                
            );
            print_r(json_encode($response)); exit;

        break;

        case 'data-calendar':
        require 'apps/appointment/models/AppAppointment.php';

        header('Content-Type: application/json');

        if ($user->roleid == "3") {
        $calendar = AppAppointment::select(['id','title','start_time AS start','end_time AS end','description AS _tooltip'])->where('admin_id',$user->id)->get()->all();
        }elseif ($user->roleid == "0") {
        $calendar = AppAppointment::select(['id','title','start_time AS start','end_time AS end','description AS _tooltip'])->where('client_id',$user->id)->get()->all();
        }else{
        $calendar=[]; 
        }
        echo json_encode($calendar);

        break;

        case 'modal-calendar':
        require 'apps/appointment/models/AppAppointment.php';

        $id = route(2, 0);
        $date = route(3, 0);
        $event = false;
        if ($id !== '' && $id !== '0') {
            $event = AppAppointment::find($id);
            $type = ORM::for_table('app_appointment_types')->find($event->type_id);
            $owners = User::select(['fullname'])->where('id',$event->admin_id)->get();
            $agente=$owners[0]->fullname;

        }
        $app_type=$type->title;

        view('modal_dashboard', [
            'event' => $event,
            'agente' => $agente,
            'app_type' => $app_type,
        ]);

        break;

        case 'render':
        jsonResponse(Dashboard::graphUpdate($user, $config));

        break;

        case 'json_income_vs_exp':
        header('Content-Type: application/json');

        $data = Dashboard::dataLastTwelveMonthsIncExp();

        echo json_encode($data);

        break;

        case 'json_d_inc_exp_month':
        header('Content-Type: application/json');

        $data = Dashboard::dataIncVsExp();

        echo json_encode($data);

        break;

        case 'json_d_chart_data':
        header('Content-Type: application/json');

        $data = Dashboard::dataIncExpD('dd');

        echo json_encode($data);

        break;

        case 'invoice_stats':
        $paid = ORM::for_table('sys_invoices')
        ->where('status', 'Paid')
        ->count();
        $unpaid = ORM::for_table('sys_invoices')
        ->where('status', 'Unpaid')
        ->count();
        $partially_paid = ORM::for_table('sys_invoices')
        ->where('status', 'Partially Paid')
        ->count();

        $arr = [
            'Paid' => $paid,
            'Unpaid' => $unpaid,
            'Partially Paid' => $partially_paid,
        ];

        $p = Misc::array_percentage($arr);

        //   api_response($p);

        echo '<table class="table table-bordered">

        <tbody>


        <tr>
        <td width="200px;"> <a href="' .
        U .
        'invoices/list/filter/unpaid/">' .
        $_L['Unpaid'] .
        ' (' .
        $unpaid .
        ')</a> </td>
        <td><div class="progress progress-small progress-thin" style="margin-bottom: 0;">
        <div style="width: ' .
        $p['Unpaid']['percentage'] .
        '%;" class="progress-bar progress-bar-danger"></div>
        </div></td>


        </tr>
        <tr>
        <td width="200px;"><a href="' .
        U .
        'invoices/list/filter/partially_paid/">' .
        $_L['Partially Paid'] .
        ' (' .
        $partially_paid .
        ')</a></td>
        <td><div class="progress progress-small progress-thin" style="margin-bottom: 0;">
        <div style="width: ' .
        $p['Partially Paid']['percentage'] .
        '%;" class="progress-bar progress-bar-success"></div>
        </div></td>


        </tr>

        <tr>
        <td width="200px;"><a href="' .
        U .
        'invoices/list/filter/paid/">' .
        $_L['Paid'] .
        ' (' .
        $paid .
        ')</a></td>
        <td><div class="progress progress-small progress-thin" style="margin-bottom: 0;">
        <div style="width: ' .
        $p['Paid']['percentage'] .
        '%;" class="progress-bar progress-bar-info"></div>
        </div></td>


        </tr>




        </tbody>
        </table>';

        break;

        case 'invoice_stats_json':
        if (has_access($user->roleid, 'transactions', 'all_data')) {
            $paid = ORM::for_table('sys_invoices')
            ->where('status', 'Paid')
            ->count();
            $unpaid = ORM::for_table('sys_invoices')
            ->where('status', 'Unpaid')
            ->count();
            $partially_paid = ORM::for_table('sys_invoices')
            ->where('status', 'Partially Paid')
            ->count();
        } else {
            $paid = ORM::for_table('sys_invoices')
            ->where('status', 'Paid')
            ->where('aid', $user->id)
            ->count();
            $unpaid = ORM::for_table('sys_invoices')
            ->where('status', 'Unpaid')
            ->where('aid', $user->id)
            ->count();
            $partially_paid = ORM::for_table('sys_invoices')
            ->where('status', 'Partially Paid')
            ->where('aid', $user->id)
            ->count();
        }

        $arr = [
            'Paid' => $paid,
            'Unpaid' => $unpaid,
            'Partially Paid' => $partially_paid,
        ];

        $p = Misc::array_percentage($arr);

        api_response($p);

        break;

        case 'update_currency':
        $currencies = Currency::where(
            'cname',
            '!=',
            $config['home_currency']
        )->get();

        view('dashboard_update_currency', [
            'currencies' => $currencies,
        ]);

        break;

        case 'lan':
        echo '<li><a href="' .
        U .
        'settings/localisation/">' .
        $_L['Localisation'] .
        '</a></li>';

        break;

        case 'tickets':
        $tickets = [];

        $admins = [];

        $tickets_tasks = [];

        if (
            isset($config['dashboard_widgets_tickets']) &&
            $config['dashboard_widgets_tickets'] == 1
        ) {
            $tickets = Ticket::orderBy('id', 'desc')
            ->limit(20)
            ->get();

            $admins = User::select(['fullname', 'id'])
            ->get()
            ->keyBy('id')
            ->all();

            $tickets_ids = array_keys($tickets->keyBy('id')->all());

            $tickets_tasks = Task::whereIn('tid', $tickets_ids)
            ->get()
            ->keyBy('tid')
            ->all();
        }

        \view('dashboard_tickets', [
            'tickets' => $tickets,
            'admins' => $admins,
            'tickets_tasks' => $tickets_tasks,
        ]);

        break;

        case 'new':
        $blade = new Blade('ui/theme/default', 'storage/cache/theme');

        echo $blade
        ->make('hello', [
            'user' => $user,
            'config' => $config,
        ])
        ->render();

        break;
    }
