<?php

namespace App\Http\Controllers\Admin\Report;

use App\Http\Controllers\Controller;
use App\Models\PurchasePayment;
use App\Models\Supplier;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;

class SupplierReportController extends Controller
{
    public function index()
    {
        return Inertia::render('Report/SupplierOpening');
    }

    public function openingSearch()
    {

        // Remove the timezone information from the string
        if (request()->start != 'null') {
            $dateStringWithoutTimezone = substr(request()->start, 0, strpos(request()->start, 'GMT'));
            // Parse the date string without timezone to a Carbon instance
            $start = Carbon::parse($dateStringWithoutTimezone)->subDay();
        } else {
            $start = null;
        }
        if (request()->end !== 'null' && request()->end !== 'undefined' && ! empty(request()->end)) {

            $dateStringWithoutTimezone = substr(request()->end, 0, strpos(request()->end, 'GMT'));
            // Parse the date string without timezone to a Carbon instance
            $end = Carbon::parse($dateStringWithoutTimezone);
        } else {
            $end = false;
        }

        if ($end) {

            $supplier = Supplier::whereBetween('opening_date', [$start, $end])
                ->when(
                    request()->location_id,
                    function ($query) {
                        if (request()->location_id != 'null') {
                            $query->where('transition_location_id', request()->location_id);
                        }
                    }
                )->with('location')->get();

            return response()->json($supplier);
        } else {
            $supplier = Supplier::whereDate('opening_date', $start)->when(
                request()->location_id,
                function ($query) {
                    if (request()->location_id != 'null') {
                        $query->where('location_id', request()->location_id);
                    }
                }
            )->with('location')->get();

            return response()->json($supplier);
        }

    }

    public function supplierDue()
    {
        return Inertia::render('Report/SupplierDueReport');
    }

    public function dueSearch()
    {

        if (isset(request()->supplier_id) && request()->supplier_id != 'null') {
            $supplier = Supplier::with('purchase', 'payment', 'returnTotal')->when(
                request()->location_id,
                function ($query) {
                    if (request()->location_id != 'null') {
                        $query->where('transition_location_id', request()->location_id);
                    }
                }
            )->with('location')->where('id', request()->supplier_id)->get();
        } else {
            $supplier = Supplier::with('purchase', 'payment', 'returnTotal')->when(
                request()->location_id,
                function ($query) {
                    if (request()->location_id != 'null') {
                        $query->where('transition_location_id', request()->location_id);
                    }
                }
            )->with('location')->get();
        }

        return response()->json($supplier);
    }


    public function supplierLedgerReport()
    {
        return Inertia::render('Report/SupplierLedgerReport');
    }
    public function supplierLedgerReportSearch()
    {
        // Remove the timezone information from the string
        if (request()->start != 'null') {
            $dateStringWithoutTimezone = substr(request()->start, 0, strpos(request()->start, 'GMT'));
            // Parse the date string without timezone to a Carbon instance

            $start = Carbon::parse($dateStringWithoutTimezone);
        } else {
            $start = null;
        }
        if (request()->end !== 'null' && request()->end !== 'undefined' && ! empty(request()->end)) {

            $dateStringWithoutTimezone = substr(request()->end, 0, strpos(request()->end, 'GMT'));
            // Parse the date string without timezone to a Carbon instance
            $end = Carbon::parse($dateStringWithoutTimezone);
        } else {
            $end = false;
        }
     $supplier=   Supplier::where('id',request()->supplier_id)->first();

        $startDate = $start ? $start->copy()->toDateString() : null;
        $endDate = $end ? $end->copy()->toDateString() : null;
        $openingBalance = DB::table('supplier_transaction_ledger_view')
            ->where('supplier_id', request()->supplier_id)
            ->where('date', '<', $startDate)
            ->selectRaw('SUM(credit) - SUM(debit) AS balance')
            ->value('balance') ?? 0;

        // Fetch main ledger
        $supplierLedger = DB::table('supplier_transaction_ledger_view')
            ->when($startDate && $endDate, function ($query) use ($startDate, $endDate) {
                $query->whereBetween('date', [$startDate, $endDate]);
            })
            ->when($startDate && !$endDate, function ($query) use ($startDate) {
                $query->whereDate('date', $startDate);
            })
            ->where('supplier_id', request()->supplier_id)
            ->orderBy('date')
            ->orderBy('sort_order')
            ->get();

        // Create opening balance row
        $openingRow = (object)[
            'date' => $startDate,
            'particulars' => 'Balance B/F',
            'invoice_no' => '--',
            'debit' => 0,
            'credit' => $openingBalance,
            'supplier_id' => request()->supplier_id,
            'order_no' => "--",
            'reference' => "--",
            'total' => $openingBalance,
            'sort_order' => 0
        ];

        // Prepend the opening row
        $supplierLedger->prepend($openingRow);






        return response()->json([
            'supplierLedger' => $supplierLedger,
            'supplier' => $supplier,
        ]);
    }



    public function supplierPaymentHistory()
    {
        $suppliers = Supplier::orderBy('name')->get(['id', 'name']);
        return Inertia::render('Report/SupplierPaymentHistory', compact('suppliers'));
    }

    public function supplierPaymentHistorySearch()
    {
        // Remove the timezone information from the string
        if (request()->start != 'null') {
            $dateStringWithoutTimezone = substr(request()->start, 0, strpos(request()->start, 'GMT'));
            // Parse the date string without timezone to a Carbon instance

            $start = Carbon::parse($dateStringWithoutTimezone);
        } else {
            $start = null;
        }
        if (request()->end !== 'null' && request()->end !== 'undefined' && ! empty(request()->end)) {

            $dateStringWithoutTimezone = substr(request()->end, 0, strpos(request()->end, 'GMT'));
            // Parse the date string without timezone to a Carbon instance
            $end = Carbon::parse($dateStringWithoutTimezone);
        } else {
            $end = false;
        }

        $startDate = $start ? $start->copy()->toDateString() : null;
        $endDate = $end ? $end->copy()->toDateString() : null;

        $supplierId = request()->supplierId;

        $query =PurchasePayment::with('supplier')
            ->when($startDate, function ($q) use ($startDate) {
                $q->whereDate('date', '>=', $startDate);
            })
            ->when($endDate, function ($q) use ($endDate) {
                $q->whereDate('date', '<=', $endDate);
            })
            ->when($supplierId, function ($q) use ($supplierId) {
                if ($supplierId != 'null') {
                    $q->where('supplier_id', $supplierId);
                }
            })
            ->orderBy('date', 'desc');

        $payments = $query->get();

        return response()->json($payments);
    }   
}
