<?php
namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\DepositToAccountRefModel;
use App\Libraries\QuickbooksAccountsLibrary;

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

        $session     = session();
        $realmId     = $session->get('realmid');
        $accessToken = $session->get('access_token');
        if (! $realmId || ! $accessToken) {
            return $this->response->setJSON([
                'status'  => 'error',
                'message' => 'Not connected to QuickBooks.',
            ]);
        }

        $model = new DepositToAccountRefModel();
        $lib   = new QuickbooksAccountsLibrary();
        try {
            $lib->pullAccounts($realmId, $accessToken, $model);
        } catch (\Throwable $e) {
            return $this->response->setJSON([
                'status'  => 'error',
                'message' => $e->getMessage(),
            ]);
        }

        return $this->response->setJSON([
            'status'  => 'success',
            'message' => 'Accounts pulled successfully.',
        ]);
    }
}
