<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\MenuModel;
use App\Models\PullPaymentTestModel;

class PullPaymentTest extends Controller
{
    public function index()
    {
        // 1) Must be logged in
        if (! service('auth')->loggedIn()) {
            return redirect()->to('/login');
        }

        // 2) Must be admin
        $user = service('auth')->user();
        if ((int) $user->is_admin !== 1) {
            return redirect()->to('/')->with('error', 'Access denied: Admins only.');
        }

        // 3) Load menu items (for your existing navbar) 
        $menuModel = new MenuModel();
        $menuItems = $menuModel->orderBy('order', 'ASC')->findAll();

        // 4) Check QuickBooks session
        $session     = session();
        $realmId     = $session->get('realmid');
        $accessToken = $session->get('access_token');
        $isConnected = (! empty($realmId) && ! empty($accessToken));

        // 5) Gather user input
        $request  = service('request');
        $fromDate = $request->getGetPost('from_date');
        $toDate   = $request->getGetPost('to_date');
        $action   = $request->getPost('action');

        // Prepare data for the view
        $viewData = [
            'menuItems'   => $menuItems,
            'isConnected' => $isConnected,
            'error'       => null,
            'from_date'   => $fromDate ?? '',
            'to_date'     => $toDate   ?? '',
            'dbResults'   => [],
        ];

        // 6) If user clicked "fetch_payments" and we are connected
        if ($action === 'fetch_payments' && $isConnected && $fromDate && $toDate) {
            try {
                $model = new PullPaymentTestModel();
                // Fetch from QBO & upsert to undeposited_funds
                $fetchResult = $model->fetchPayments($fromDate, $toDate, $realmId, $accessToken);

                if ($fetchResult['error']) {
                    $viewData['error'] = $fetchResult['error'];
                } else {
                    // If we want to show the new data, we can pass it along to the view
                    $viewData['dbResults'] = $fetchResult['records'];
                }

            } catch (\Exception $e) {
                $viewData['error'] = 'Exception: ' . $e->getMessage();
            }
        }

        // Render the view
        return view('pullpaymenttest/index', $viewData);
    }

    // Provide a simple method to initiate QBO connection; redirect back here afterwards
    public function connectQBO()
    {
        // Just send them to your existing route that starts OAuth
        return redirect()->to('qboauth/connect');
    }
}
