<?php

namespace App\Controllers;

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

class AuditDuplicatesTransactions 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 left nav
        $menuModel = new MenuModel();
        $menuItems = $menuModel->orderBy('order', 'ASC')->findAll();

        // 4) Grab date input (GET or POST)
        $request    = service('request');
        $fromDate   = $request->getGetPost('from_date');
        $toDate     = $request->getGetPost('to_date');
        $viewSelect = $request->getGetPost('view_select') ?? 'duplicates';

        // 5) If user changes view dropdown, redirect to the correct controller
        if ($viewSelect === 'pull') {
            // Go back to the AuditQuickbooks "pull" page
            return redirect()->to(
                '/auditquickbooks'
                . '?from_date=' . urlencode($fromDate)
                . '&to_date='   . urlencode($toDate)
                . '&view_select=pull'
            );
        } elseif ($viewSelect === 'audit') {
            // Go to AuditLiabilityAccounts
            return redirect()->to(
                '/auditliabilityaccounts'
                . '?from_date=' . urlencode($fromDate)
                . '&to_date='   . urlencode($toDate)
                . '&view_select=audit'
            );
        }
        // If $viewSelect === 'duplicates', we stay here.

        // 6) Decide if we run the “getDuplicateTransactions” query or not
        $model   = new AuditQuickbooksModel();
        $results = [];

        // Only run the query if both dates are provided
        if (!empty($fromDate) && !empty($toDate)) {
            $results = $model->getDuplicateTransactions($fromDate, $toDate);
        }

        // 7) Build data for the view
        $data = [
            'results'     => $results,
            'from_date'   => $fromDate,
            'to_date'     => $toDate,
            'view_select' => 'duplicates',
            'error'       => '',
            'menuItems'   => $menuItems,
        ];

        // 8) Render the view
        return view('auditquickbooks/auditduplicatetransactions', $data);
    }
}
