<?php

namespace App\Http\Controllers\Admin;

use App\Constants\Status;
use App\Http\Controllers\Controller;
use App\Models\Nominee;
use App\Models\SavingAccount;

class SavingsAccountController extends Controller
{
    public function all()
    {
        $pageTitle = "Savings Accounts";
        $savingAccounts = $this->baseQuery();
        return view('admin.savings.account.list', compact('pageTitle', 'savingAccounts'));
    }

    public function active()
    {
        $pageTitle = "Active Savings Accounts";
        $savingAccounts = $this->baseQuery('running');
        return view('admin.savings.account.list', compact('pageTitle', 'savingAccounts'));
    }

    public function matured()
    {
        $pageTitle = "Matured Savings Accounts";
        $savingAccounts = $this->baseQuery('matured');
        return view('admin.savings.account.list', compact('pageTitle', 'savingAccounts'));
    }

    public function closed()
    {
        $pageTitle = "Closed Savings Accounts";
        $savingAccounts = $this->baseQuery('closed');
        return view('admin.savings.account.list', compact('pageTitle', 'savingAccounts'));
    }

    public function baseQuery($scope = 'query')
    {
        return SavingAccount::$scope()
            ->with('user')
            ->searchable(['user:username', 'user:mobile', 'account_id'])
            ->dateFilter()
            ->latest('id')
            ->paginate(getPaginate());
    }

    public function accountDetails($id)
    {
        $account   = SavingAccount::with('user', 'dpsPlan', 'dpsPlan.organization')->findOrFail($id);
        $pageTitle = "Savings Account - " . $account->account_id;
        $widget['account_balance']  = $account->balance;
        $widget['paid_installment'] = $account->installments->where('status', Status::INSTALLMENT_PAID)->count();
        $widget['due_installment']  = $account->installments->where('status', Status::INSTALLMENT_UNPAID)->sum('amount');
        $widget['maturity_amount']  = $account->dpsPlan?->maturity_amount;
        $installments = $account->installments()->latest()->paginate(getPaginate());

        return view('admin.savings.account.account_details', compact('pageTitle', 'widget', 'account', 'installments'));
    }

    public function nomineeDetails($id)
    {
        $pageTitle = "Nominee Details";
        $nominee = Nominee::with('user')->findOrFail($id);
        return view('admin.savings.account.nominee_details', compact('pageTitle', 'nominee'));
    }
}
