<?php
namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\DepositHistoryModel;

class DepositHistory extends Controller
{
    public function index()
    {
        if (! service('auth')->loggedIn()) {
            return redirect()->to('/login');
        }
        $user = service('auth')->user();
        if ((int) ($user->is_admin ?? 0) !== 1) {
            return redirect()->to('/')->with('error', 'Access denied: Admins only.');
        }

        $model    = new DepositHistoryModel();
        $deposits = $model->getAllDeposits();

        return view('deposit_history/index', ['deposits' => $deposits]);
    }

    public function loadView()
    {
        $request = service('request');
        $pane    = $request->getGet('pane');
        $id      = $request->getGet('id');

        $model = new DepositHistoryModel();

        if ($pane === 'left') {
            $deposits = $model->getAllDeposits();
            return view('deposit_history/left/list', ['deposits' => $deposits]);
        }

        if ($pane === 'middle') {
            if ($id) {
                $details = $model->getDepositWithLines((int) $id);
            } else {
                $details = ['deposit' => null, 'lines' => []];
            }
            return view('deposit_history/middle/details', $details);
        }

        return '';
    }
}
