<?php

namespace App\Controllers;

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

class SourceToSaleDeposits 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
        $today        = date('Y-m-d');
        $firstOfMonth = date('Y-m-01');
        $fromDate     = $this->request->getVar('from_date') ?: $firstOfMonth;
        $toDate       = $this->request->getVar('to_date')   ?: $today;

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

        $fetchParams = [
            'from_date'    => $fromDate,
            'to_date'      => $toDate,
            'limit'        => $limit,
            'current_page' => $currentPage,
        ];
        $dataResult = $model->getEarliestDepositsWithinRange($fetchParams);

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

        /**
         * 7) Check if user clicked "Export CSV".
         *    If so, output CSV for the *currently displayed* rows, then exit.
         */
        if ($this->request->getVar('export_csv') === '1') {
            return $this->exportCsv($dataResult['results']);
        }

        // 8) Otherwise, render normal HTML view
        $viewData = [
            'menuItems'    => $menuItems,
            'limitOptions' => $limitOptions,
            'limit'        => $limit,
            'currentPage'  => $dataResult['currentPage'],
            'totalRows'    => $dataResult['totalRows'],
            'totalPages'   => $dataResult['totalPages'],

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

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

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

    /**
     * Generate and return a CSV file from an array of results, then exit.
     */
    private function exportCsv(array $results)
    {
        // Prepare CSV headers
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment;filename="source_to_sale_export.csv"');
        header('Cache-Control: max-age=0');

        // Open the output stream
        $fp = fopen('php://output', 'w');

        // CSV column headers
        fputcsv($fp, [
            'Deal ID',
            'COB#',
            'Deposit Date',
            'Phone Number',
            'First Name',
            'Last Name',
            'Business',
            'Email',
            'Address',
            'City',
            'State',
            'Zip',
            'Unit Value',
            'Plus Doc Fee',
            'Lead Source',
            'ISO Country Code'
        ]);

        // Write each row
        foreach ($results as $row) {
            // Safely parse numeric portion from "unit_value"
            $unitValueParsed = (float) str_replace(['$', ','], '', $row['unit_value']);
            // Add $194.00
            $docFeeAmount = $unitValueParsed + 194.00;
            // No commas for CSV numeric portion
            $docFeePlain = number_format($docFeeAmount, 2, '.', '');

            // If lead_source_name is null or empty, set it to 'N/A'
            $leadSource = $row['lead_source_name'] ?? 'N/A';

            fputcsv($fp, [
                $row['deal_id'],
                'COB-D' . $row['cob_number'],
                $row['deposit_date'],
                $row['phone_number'],
                $row['first_name'],                  
                $row['last_name'],                  
                $row['business_name'],
                $row['email'],
                $row['address'],
                $row['city'],
                $row['state'],
                $row['zipcode'],
                $row['unit_value'],
                $docFeePlain,
                $leadSource,
                'ISO 3166-2:US'
            ]);
        }

        fclose($fp);
        // End the response to prevent the HTML view from rendering
        exit;
    }
}
