<?php

namespace App\Http\Controllers\Admin\Report;

use App\Http\Controllers\Controller;
use App\Models\PurchaseMaster;
use App\Models\PurchaseReturnMaster;
use App\Models\WarehouseStock;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;

class PurchaseReportController extends Controller
{
    public function summary()
    {
        return Inertia::render('Report/PurchaseSummary');
    }

    public function invoice()
    {
        return Inertia::render('Report/PurchaseInvoice');
    }

    public function details()
    {
        return Inertia::render('Report/PurchaseDetails');
    }

    public function search()
    {
        // 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) {
            $purchase = DB::table('purchase_summary_view')
                ->when(request()->location_id != 'null', function ($query) {
                    $query->where('warehouse_id', request()->location_id);
                })
                ->whereBetween('purchase_date', [$start->addDay(1), $end->addDay(1)])
                ->when(!empty(request()->supplier) && request()->supplier != "undefined" && request()->supplier != "null", function ($quarry) {
                    $quarry->where('supplier_id', request()->supplier);
                })->get();
        } else {
            $purchase = DB::table('purchase_summary_view')->when(request()->location_id != 'null', function ($query) {
                $query->where('warehouse_id', request()->location_id);
            })->whereDate('purchase_date', $start->addDay(1))->when(!empty(request()->supplier) && request()->supplier != "undefined" && request()->supplier != "null", function ($quarry) {
                $quarry->where('supplier_id', request()->supplier);
            })->get();
        }

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

    public function invoiceSearch()
    {
        // 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) {
            $purchase = PurchaseMaster::selectRaw('id, supplier_id,purchase_date as date')
                ->when(request()->company_id != 'null', function ($query) {
                    $query->where('supplier_id', request()->company_id);
                })
                ->with([
                    'PurchaseDetalis' => function ($query) {
                        $query->selectRaw('purchase_master_id, attribute_id, sum(quantity) as qty, sum(unit_price) as purchase, sum(unit_price_total) as total')
                            ->groupBy('purchase_master_id', 'attribute_id')->with('attribute');
                    },
                ])
                ->groupBy('id', 'supplier_id', 'purchase_date')
                ->with('supplier')

                ->whereBetween('purchase_date', [$start, $end])

                ->orderBY('purchase_date', 'ASC')
                ->get();
        } else {
            $purchase = PurchaseMaster::selectRaw('id, supplier_id,purchase_date as date')
                ->when(request()->company_id != 'null', function ($query) {
                    $query->where('supplier_id', request()->company_id);
                })
                ->with([
                    'PurchaseDetalis' => function ($query) {
                        $query->selectRaw('purchase_master_id, attribute_id, sum(quantity) as qty, sum(unit_price) as purchase, sum(unit_price_total) as total')
                            ->groupBy('purchase_master_id', 'attribute_id')->with('attribute');
                    },
                ])
                ->groupBy('id', 'supplier_id', 'purchase_date')
                ->with('supplier')
                ->whereDate('purchase_date', $start)

                ->orderBY('purchase_date', 'ASC')
                ->get();
        }

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

    public function detailsSearch()
    {


        // 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) {

            $purchase = DB::table('purchase_details_view')->where('location_id', request()->location_id)->when(request()->productId != "undefined" && request()->productId != "null", function ($quarry) {
                $quarry->where('attribute_id', request()->productId);
            })->when(!empty(request()->supplier) && request()->supplier != "undefined" && request()->supplier != "null", function ($quarry) {
                $quarry->where('supplier_id', request()->supplier);
            })->whereBetween('date', [$start->addDay(1), $end->addDay(1)])
            ->orderBy('date', 'DESC')
            ->get();
        } else {
            $purchase = DB::table('purchase_details_view')->where('location_id', request()->location_id)->when(request()->productId  != "undefined"  && request()->productId != "null", function ($quarry) {
                $quarry->where('attribute_id', request()->productId);
            })
                ->when(!empty(request()->supplier) && request()->supplier != "undefined" && request()->supplier != "null", function ($quarry) {
                    $quarry->where('supplier_id', request()->supplier);
                })

                ->whereDate('date', $start->addDay(1))
                ->orderBy('date', 'DESC')
                ->get();
        }



        $discountSum = DB::table('purchase_masters')
            ->when(request()->client_id, function ($query) {
                return $query->where('client_id', request()->client_id);
            })
            ->when($start && $end, function ($query) use ($start, $end) {
                return $query->whereBetween('created_at', [$start->toDateString(), $end->toDateString()]);
            })
            ->when($start && !$end, function ($query) use ($start) {
                return $query->whereDate('created_at', '=', $start->toDateString());
            })
            ->where('warehouse_id', request()->location_id)
            ->sum('after_discount');

        return response()->json([
            'purchase' => $purchase,
            'discountSum' => $discountSum
        ]);
    }

    public function purchaseReturnReport()
    {
        return Inertia::render('Report/PurchaseRetutnReport');
    }

    public function purchaseReturnSearch()
    {

        // 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) {

        //     $salse = PurchaseReturnMaster::selectRaw('*')->with('details', 'supplier')

        //         ->whereBetween('return_date', [$start, $end])
        //         ->orderBY('return_date', 'ASC')
        //         ->get();
        // } else {

        //     $salse = PurchaseReturnMaster::selectRaw('*')->with('details', 'supplier')
        //         ->whereDate('return_date', $start)
        //         ->get();
        // }
        $salse = DB::table('purchase_return_details_view')
            ->when($start && $end, function ($query) use ($start, $end) {
                return $query->whereBetween('return_date', [$start->toDateString(), $end->toDateString()]);
            })
            ->when($start && !$end, function ($query) use ($start) {
                return $query->whereDate('return_date', '=', $start->toDateString());
            })
            ->get();

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

    public function purchaseReturnDelete()
    {
        $purchaseReturn = PurchaseReturnMaster::where('id', request()->id)->first();
        
        if (!$purchaseReturn) {
            return response()->json(['error' => 'Purchase return not found'], 404);
        }

        // Get warehouse_id based on return type
        $warehouseId = null;
        if ($purchaseReturn->type === 'regular' && $purchaseReturn->purchase_invoice_no) {
            $purchase = PurchaseMaster::where('id', $purchaseReturn->purchase_invoice_no)->first();
            if ($purchase) {
                $warehouseId = $purchase->warehouse_id;
            }
        } else {
            // For direct returns, get warehouse_id from request or use shop_id
            $warehouseId = request()->warehouse_id ?? auth()->user()->shop_id;
        }

        if (!$warehouseId) {
            return response()->json(['error' => 'Warehouse ID not found'], 400);
        }

        // Get return details to restore stock
        $returnDetails = \App\Models\PurchaseReturnDetails::where('purchase_return_master_id', $purchaseReturn->id)->get();
        
        foreach ($returnDetails as $detail) {
            WarehouseStock::where('warehouse_id', $warehouseId)
                ->where('attribute_id', $detail->attribute_id)
                ->update([
                    'quantity' => DB::raw('quantity + ' . $detail->return_qty),
                ]);
        }

        // Store type before deletion
        $type = $purchaseReturn->type ?? 'regular';
        
        // Delete the return master (details will be deleted via cascade)
        $purchaseReturn->delete();

        // Get updated list based on type
        $purchaseReturnList = PurchaseReturnMaster::with('supplier', 'invoice', 'details', 'returnProduct', 'purchaseDetails', 'purchaseDetail')
            ->where('type', $type)
            ->where('shop_id', auth()->user()->shop_id)
            ->orderby('id', 'DESC')
            ->get();

        // Get reference number based on type
        $lastReturn = PurchaseReturnMaster::where('type', $type)->orderby('reference_no', 'DESC')->first();
        $reference = invoice_no($lastReturn?->id ?? false, $type === 'direct' ? 'DPR' : 'PR');

        return response()->json([
            'success' => 'Data Delete successfully', 
            'reference' => $reference, 
            'purchaseReturn' => $purchaseReturnList
        ]);
    }
}
