<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\MenuModel;
use App\Models\AuditPaymentsModel;  // <- Our new model
use CodeIgniter\HTTP\RedirectResponse;

class AuditPayments 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) Handle limit & pagination
        $limitOptions = [10, 25, 50, 100, 500, 'ALL'];
        $limit = $this->request->getVar('limit') ?? 'ALL';
        if (! in_array($limit, $limitOptions, true)) {
            $limit = 'ALL';
        }
        $currentPage = (int) ($this->request->getVar('page') ?? 1);
        if ($currentPage < 1) {
            $currentPage = 1;
        }

        // 5) Filters: date range + p_type
        $today        = date('Y-m-d');
        $firstOfMonth = date('Y-m-01');
        $fromDate     = $this->request->getVar('from_date') ?: $firstOfMonth;
        $toDate       = $this->request->getVar('to_date')   ?: $today;
        $pTypeFilter  = $this->request->getVar('p_type')    ?? 'ALL';  // 'ALL' means no restriction

        // 6) Retrieve data from model
        $model = new AuditPaymentsModel();

        // We'll first get the distinct p_type values (for the dropdown).
        $paymentTypes = $model->getDistinctPaymentTypes();

        // Then we get the main records
        $fetchParams = [
            'from_date'    => $fromDate,
            'to_date'      => $toDate,
            'p_type'       => $pTypeFilter,
            'limit'        => $limit,
            'current_page' => $currentPage,
        ];
        $dataResult = $model->getAuditPayments($fetchParams);

        // $dataResult should contain:
        //   'results' => array of rows
        //   'totalRows' => total number of filtered rows
        //   'totalPages' => total number of pages
        //   'currentPage' => $currentPage

        // 7) Pass everything to the view
        $viewData = [
            'menuItems'    => $menuItems,
            'limitOptions' => $limitOptions,
            'limit'        => $limit,
            'currentPage'  => $dataResult['currentPage'],
            'totalRows'    => $dataResult['totalRows'],
            'totalPages'   => $dataResult['totalPages'],

            // filters
            'fromDate'     => $fromDate,
            'toDate'       => $toDate,
            'pTypeFilter'  => $pTypeFilter,
            'paymentTypes' => $paymentTypes,

            // the actual data
            'results'      => $dataResult['results'],
        ];

        return view('auditpayments/index', $viewData);
    }

    /**
     * Inline edit for the "notes" column in bbt_deal_payments table.
     */
    public function updateField()
    {
        // Must be logged in & admin
        if (! service('auth')->loggedIn()) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Not logged in.',
            ]);
        }
        $user = service('auth')->user();
        if ((int) $user->is_admin !== 1) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Access denied.',
            ]);
        }

        // Retrieve POST data
        $id    = $this->request->getPost('id');
        $field = $this->request->getPost('field');
        $value = $this->request->getPost('value');

        if (empty($id) || empty($field)) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Missing rowId or field name.',
            ]);
        }

        // We only allow editing "notes" in this example
        if ($field !== 'notes') {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Only the "notes" field can be edited.',
            ]);
        }

        // Update in DB
        $db = db_connect();
        $builder = $db->table('bbt_deal_payments');
        $builder->where('id', $id);
        try {
            $builder->update([$field => $value]);
            if ($db->affectedRows() >= 0) {
                return $this->response->setJSON([
                    'success' => true,
                    'message' => 'Notes updated successfully.',
                ]);
            } else {
                return $this->response->setJSON([
                    'success' => false,
                    'message' => 'No rows were updated.',
                ]);
            }
        } catch (\Exception $e) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Exception: ' . $e->getMessage(),
            ]);
        }
    }
}
