<?php namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\LoanModel;
use App\Models\PaymentModel;
use App\Models\NotificationModel;

class Loans extends BaseController
{
    public function index()
    {
        $db = \Config\Database::connect();
        $loans = $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")->getResultArray();
        echo view('layouts/admin_header', ['title'=>'Loans']);
        echo view('admin/loans', compact('loans'));
        echo view('layouts/admin_footer');
    }

    public function view($id)
    {
        $db = \Config\Database::connect();
        $loan = $db->query("SELECT l.*, u.name as user_name, u.email, 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 WHERE l.id = ?", [$id])->getRowArray();
        if (!$loan) return redirect()->back()->with('error','Loan not found');

        $payments = (new PaymentModel())->where('loan_id', $id)->orderBy('due_date','ASC')->findAll();
        echo view('layouts/admin_header', ['title'=>'Loan #'.$loan['loan_uid']]);
        echo view('admin/loan_view', compact('loan','payments'));
        echo view('layouts/admin_footer');
    }

    public function approve($id)
    {
        $loanModel = new LoanModel();
        if (!$loanModel->find($id)) return redirect()->back()->with('error','Loan not found');
        $loanModel->update($id,['status'=>'approved','updated_at'=>date('Y-m-d H:i:s')]);
        (new NotificationModel())->insert(['user_id'=>$loanModel->find($id)['user_id'],'title'=>'Loan Approved','body'=>'Your loan has been approved.','created_at'=>date('Y-m-d H:i:s')]);
        return redirect()->back()->with('success','Loan approved.');
    }
}
