<?php namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\LoanModel;
use App\Models\LoanProductModel;
use App\Models\UserModel;
use Config\Services;

class Dashboard extends BaseController
{
    public function index()
    {
        $loanModel = new LoanModel();
        $productModel = new LoanProductModel();
        $userModel = new UserModel();

        $totalLoans = $loanModel->countAll();
        $pending = $loanModel->where('status','pending')->countAllResults(false);
        $disbursed = $loanModel->where('status','disbursed')->countAllResults(false);

        $outstanding = (float) \Config\Database::connect()->table('payments')->selectSum('amount')->where('status !=','paid')->get()->getRowArray()['amount'] ?? 0;

        $db = \Config\Database::connect();
        $recentRaw = $db->query("SELECT l.*, u.name as user_name, p.name as product_name FROM loans l LEFT JOIN users u ON l.user_id=u.id LEFT JOIN loan_products p ON l.product_id=p.id ORDER BY l.created_at DESC LIMIT 8")->getResultArray();
        $recent = $recentRaw;

        $chartData = [];
        for ($i=6;$i>=0;$i--){
            $day = date('Y-m-d', strtotime("-{$i} days"));
            $count = $db->table('loans')->where('DATE(created_at)', $day)->countAllResults(false);
            $chartData[] = ['label'=>date('d M', strtotime($day)),'count'=>$count];
        }

        $products = $productModel->findAll();

        echo view('layouts/admin_header', ['title'=>'Dashboard']);
        echo view('admin/dashboard', compact('totalLoans','pending','disbursed','outstanding','recent','chartData','products'));
        echo view('layouts/admin_footer');
    }
}
