<?php

namespace App\Http\Controllers;

use App\Lib\Backend;
use App\Models\AppSession;
use App\Models\BillingReport;
use App\Models\CareMonth;
use App\Models\ClaimEDI;
use App\Models\ClientProChange;
use App\Models\Company;
use App\Models\Customer;
use App\Models\CustomerTransaction;
use App\Models\GiftCard;
use App\Models\Handout;
use App\Models\Invoice;
use App\Models\InvoiceTransaction;
use App\Models\MBClaim;
use App\Models\Measurement;
use App\Models\Bill;
use App\Models\Claim;
use App\Models\Client;
use App\Models\McpRequest;
use App\Models\McCodeCheck;
use App\Models\Note;
use App\Models\Pack;
use App\Models\Pro;
use App\Models\Product;
use App\Models\ProFavorite;
use App\Models\ProGeneralAvailability;
use App\Models\ProProAccess;
use App\Models\ProRate;
use App\Models\ProSpecificAvailability;
use App\Models\ProSpecificUnavailability;
use App\Models\ProTeam;
use App\Models\ProTextShortcut;
use App\Models\ProTransaction;
use App\Models\Shipment;
use App\Models\SupplyOrder;
use App\Models\Team;
use App\Models\Ticket;
use App\Models\AccountInvite;
use App\Models\ClientMeasurementDaysPerMonth;
use App\Models\ClientBDTDevice;
use App\Models\ClientMemo;
use Carbon\Carbon;
use Cassandra\Custom;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use MongoDB\Driver\Session;
use PDF;
use DateTime;
use DateTimeZone;
use Illuminate\Http\Request;
use App\Models\SegmentTemplate;
use App\Models\VisitTemplate;
use App\Models\VisitTemplateSegmentTemplate;
use App\Models\VisitTemplateAccess;

class InvoiceController extends Controller
{

    private static $PAGE_SIZE = 25;

    public function companies(Request $request) {
        $records = Company::orderBy('name', 'ASC')->where('is_active', true)->paginate(InvoiceController::$PAGE_SIZE);
        return view ('app.invoice-center.companies', compact('records'));
    }

    public function customers(Request $request) {
        $records = Customer::orderBy('created_at', 'DESC');
        $company = null;
        if($request->input('companyUid')) {
            $company = Company::where('uid', $request->input('companyUid'))->first();
            if($company) {
                $records = $records->where('company_id', $company->id);
            }
        }
        $records = $records->paginate(InvoiceController::$PAGE_SIZE);
        return view ('app.invoice-center.customers', compact('records', 'company'));
    }

    public function giftCards(Request $request) {
        $records = GiftCard::orderBy('created_at', 'DESC');
        $company = null;
        if($request->input('companyUid')) {
            $company = Company::where('uid', $request->input('companyUid'))->first();
            if($company) {
                $records = $records->where('company_id', $company->id);
            }
        }
        $records = $records->paginate(InvoiceController::$PAGE_SIZE);
        return view ('app.invoice-center.gift-cards', compact('records', 'company'));
    }

    public function invoices(Request $request) {
        $records = Invoice::orderBy('created_at', 'DESC');
        $customer = null;
        if($request->input('customerUid')) {
            $customer = Customer::where('uid', $request->input('customerUid'))->first();
            if($customer) {
                $records = $records->where('customer_id', $customer->id);
            }
        }
        $records = $records->paginate(InvoiceController::$PAGE_SIZE);
        return view ('app.invoice-center.invoices', compact('records', 'customer'));
    }

    public function customerTransactions(Request $request) {
        $records = CustomerTransaction::orderBy('created_at', 'DESC');
        $customer = null;
        if($request->input('customerUid')) {
            $customer = Customer::where('uid', $request->input('customerUid'))->first();
            if($customer) {
                $records = $records->where('customer_id', $customer->id);
            }
        }
        $records = $records->paginate(InvoiceController::$PAGE_SIZE);
        return view ('app.invoice-center.customer-transactions', compact('records', 'customer'));
    }

    public function invoiceTransactions(Request $request) {
        $records = InvoiceTransaction::orderBy('created_at', 'DESC');
        $invoice = null;
        if($request->input('invoiceUid')) {
            $invoice = Invoice::where('uid', $request->input('invoiceUid'))->first();
            if($invoice) {
                $records = $records->where('invoice_id', $invoice->id);
            }
        }
        $records = $records->paginate(InvoiceController::$PAGE_SIZE);
        return view ('app.invoice-center.invoice-transactions', compact('records', 'invoice'));
    }

    private function getICCustomer($sessionKey) {
        $customer = false;
        if($sessionKey) {
            Cookie::queue('sessionKey', $sessionKey);
        }
        else {
            $session = get_current_session();
            if(!$session) {
                abort(403);
            }
            else {
                $customer = Customer::where('id', $session->customer_id)->first();
                if(!$customer) {
                    abort(403);
                }
            }
        }
        return $customer;
    }

    public function icPayInvoice(Request $request, $invoiceUid, $sessionKey = '') {
        $customer = $this->getICCustomer($sessionKey);
        if(!$customer) {
            return redirect(route('icPayInvoice', ['invoiceUid' => $invoiceUid]));
        }
        $invoice = Invoice::where('uid', $invoiceUid)->where('is_active', true)->first();
        if (!$invoice) abort(404);
        $company = $customer->company;
        return view('app.invoice-center.ic-pay-invoice', compact('invoice', 'customer', 'company'));
    }
    public function icPaymentMethods(Request $request, $invoiceUid, $sessionKey = '') {
        $customer = $this->getICCustomer($sessionKey);
        if(!$customer) {
            abort(404);
        }
        $company = $customer->company;
        return view('app.invoice-center.ic-payment-methods', compact('customer', 'company'));
    }

    public function icCustomerPortal(Request $request, $sessionKey = '') {
        $customer = $this->getICCustomer($sessionKey);
        if(!$customer) {
            return redirect(route('icCustomerPortal'));
        }
        $client = $customer->client;
        $company = $customer->company;
        return view('app.invoice-center.ic-customer-portal', compact('customer', 'company'));
    }

    public function icManageAccount(Request $request, $sessionKey = '') {
        $customer = $this->getICCustomer($sessionKey);
        if(!$customer) {
            return redirect(route('icManageAccount'));
        }
        $client = $customer->client;
        $company = $customer->company;
        return view('app.invoice-center.ic-manage-account', compact('customer', 'company', 'client'));
    }

    public function companySuggestJSON(Request $request) {
        $term = $request->input('term') ? trim($request->input('term')) : '';
        if (empty($term)) return '';
        $matches = DB::select("
SELECT company.uid,
       company.name as text
FROM company
WHERE company.name ILIKE :term
ORDER BY company.name",
            ['term' => $term . '%']
        );
        return json_encode([
            "success" => true,
            "data" => $matches
        ]);
    }

    public function clientSuggestJSON(Request $request) {
        $term = $request->input('term') ? trim($request->input('term')) : '';
        if (empty($term)) return '';

        // if multiple words in query, check for all (max 2)
        $term2 = '';
        if(strpos($term, ' ') !== FALSE) {
            $terms = explode(' ', $term);
            $term = trim($terms[0]);
            $term2 = trim($terms[1]);
        }

        if(!empty($term2)) {
            $matches = DB::select("
SELECT client.uid,
       (client.name_first || ' ' || client.name_last) as text
FROM client
WHERE (client.name_first ILIKE :term OR client.name_last ILIKE :term OR client.name_first ILIKE :term2 OR client.name_last ILIKE :term2)
ORDER BY client.name_first, client.name_last",
                ['term' => $term . '%', 'term2' => $term2 . '%']
            );
        }
        else {
            $matches = DB::select("
SELECT client.uid,
       (client.name_first || ' ' || client.name_last) as text
FROM client
WHERE (client.name_first ILIKE :term OR client.name_last ILIKE :term)
ORDER BY client.name_first, client.name_last",
                ['term' => $term . '%']
            );
        }

        return json_encode([
            "success" => true,
            "data" => $matches
        ]);
    }

    public function customerSuggestJSON(Request $request) {
        $term = $request->input('term') ? trim($request->input('term')) : '';
        if (empty($term)) return '';

        // if multiple words in query, check for all (max 2)
        $term2 = '';
        if(strpos($term, ' ') !== FALSE) {
            $terms = explode(' ', $term);
            $term = trim($terms[0]);
            $term2 = trim($terms[1]);
        }

        if(!empty($term2)) {
            $matches = DB::select("
SELECT customer.uid,
       (client.name_first || ' ' || client.name_last || ' (' || company.name || ')') as text
FROM client join customer on client.id = customer.client_id join company on customer.company_id = company.id
WHERE (client.name_first ILIKE :term OR client.name_last ILIKE :term OR client.name_first ILIKE :term2 OR client.name_last ILIKE :term2)
ORDER BY client.name_first, client.name_last",
                ['term' => $term . '%', 'term2' => $term2 . '%']
            );
        }
        else {
            $matches = DB::select("
SELECT customer.uid,
       (client.name_first || ' ' || client.name_last || ' (' || company.name || ')') as text
FROM client join customer on client.id = customer.client_id join company on customer.company_id = company.id
WHERE (client.name_first ILIKE :term OR client.name_last ILIKE :term)
ORDER BY client.name_first, client.name_last",
                ['term' => $term . '%']
            );
        }

        return json_encode([
            "success" => true,
            "data" => $matches
        ]);
    }

    public function customerInvoicesJSON(Request $request, Customer $customer) {
        $invoices = [];
        foreach ($customer->invoices as $invoice) {
            $invoices[] = [
                "uid" => $invoice->uid,
                "text" => $invoice->displayName()
            ];
        }
        return json_encode([
            "success" => true,
            "data" => $invoices
        ]);
    }
   
}
