<?php

namespace App\Controllers;

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

class SalesReceipts 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.');
        }

        $menuModel   = new MenuModel();
        $menuItems   = $menuModel->orderBy('order', 'ASC')->findAll();
        $session     = session();
        $realmId     = $session->get('realmid');
        $accessToken = $session->get('access_token');
        $isConnected = (! empty($realmId) && ! empty($accessToken));

        $fromDate     = $this->request->getGet('from_date');
        $toDate       = $this->request->getGet('to_date');
        $amazonHidden = $this->request->getGet('amazon_hidden') === '1'; // or false by default

        $dbResults = [];
        if ($isConnected && ! empty($fromDate) && ! empty($toDate)) {
            $auditQuickbooksModel = new AuditQuickbooksModel();
            $query = $auditQuickbooksModel
                ->where('txn_date >=', $fromDate)
                ->where('txn_date <=', $toDate);

            if ($amazonHidden) {
                $query->where('doc_number NOT LIKE', 'INVB-A%');
            }

            $dbResults = $query->orderBy('id', 'DESC')->findAll();
        }

        return view('salesreceipts/index', [
            'menuItems'    => $menuItems,
            'isConnected'  => $isConnected,
            'from_date'    => $fromDate ?? '',
            'to_date'      => $toDate   ?? '',
            'dbResults'    => $dbResults,
            'amazonHidden' => $amazonHidden
        ]);
    }
}
