<?php

namespace App\Http\Controllers\Admin\Report;

use App\Http\Controllers\Controller;
use App\Models\Bank;
use App\Models\MobileBanking;
use App\Models\SalesDetails;
use App\Models\SalesMaster;
use App\Models\Shop;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;

class SalseReportController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return Inertia::render('Report/SalseReport');
    }

    public function shop()
    {
        $shop = Shop::where('id', Auth::user()->shop_id)->first();

        return response()->json(['shop' => $shop]);
    }

    /**
     * Show the form for creating a new resource.
     */
    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);
        } 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;
        }

        $salesDetails = DB::table('daily_product_sales_summary_view')

            ->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('date', [$start->toDateString(), $end->toDateString()]);
            })
            ->when($start && ! $end, function ($query) use ($start) {
                return $query->whereDate('date', '=', $start->toDateString());
            })
            ->where('location_id', request()->location_id)
            ->get();

        $discountSum = DB::table('sales_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('location_id', request()->location_id)
            ->sum('after_discount');

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

    public function saleSearch()
    {

        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;
        }

        $salesSummary = DB::table('sales_details_summary_view')

            ->when(request()->mobilebank_id, function ($query) {
                return $query->where('mobilebank_id', request()->mobilebank_id);
            })
            ->when(request()->bank_id, function ($query) {
                return $query->where('bank_id', request()->bank_id);
            })
            ->when($start && $end, function ($query) use ($start, $end) {
                return $query->whereBetween('date', [$start->toDateString(), $end->toDateString()]);
            })
            ->when($start && ! $end, function ($query) use ($start) {
                return $query->whereDate('date', '=', $start->toDateString());
            })
            ->when(request()->attribute_id && request()->attribute_id != 'null' && request()->attribute_id != 'undefine' && request()->attribute_id != 'false', function ($query) {
                return $query->where('attribute_id', request()->attribute_id);
            })
            ->when(request()->customer_id && request()->customer_id != 'null' && request()->customer_id != 'undefine', function ($query) {
                return $query->where('client_id', request()->customer_id);
            })
            ->where('location_id', request()->location_id)
            ->orderBy('date', 'DESC')
            ->get();

        $discountSum = DB::table('sales_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());
            })
            ->when(request()->customer_id && request()->customer_id != 'null' && request()->customer_id != 'undefine', function ($query) {
                return $query->where('client_id', request()->customer_id);
            })
            ->where('location_id', request()->location_id)
            ->sum('after_discount');

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

    public function searchdisocunt(Request $request)
    {
        $customerId = $request->customer_id ?? null;
        $rawStart = $request->start ?? null;
        $rawEnd = $request->end ?? null;
        $location_id = $request->location_id ?? null;

        // Normalize strings like: "Wed Aug 14 2025 00:00:00 GMT+0600 ..."
        $normalize = function ($value) {
            if (! $value || $value === 'null' || $value === 'undefined') {
                return null;
            }
            $pos = strpos($value, 'GMT');

            return $pos !== false ? trim(substr($value, 0, $pos)) : $value;
        };

        $startStr = $normalize($rawStart);
        $endStr = $normalize($rawEnd);

        if (! $startStr) {
            return response()->json(['error' => 'start date is required'], 422);
        }

        // Define Dhaka-day window, then convert to UTC for querying created_at
        $startDhaka = Carbon::parse($startStr, 'Asia/Dhaka')->startOfDay();
        $endDhaka = $endStr
            ? Carbon::parse($endStr, 'Asia/Dhaka')->endOfDay()
            : (clone $startDhaka)->endOfDay();

        $startUtc = (clone $startDhaka)->setTimezone('UTC');
        $endUtc = (clone $endDhaka)->setTimezone('UTC');

        // Query masters first (date-wise, optional customer), ignoring ONLY 'typeScope'
        $masters = SalesMaster::query()
            ->withoutGlobalScope('typeScope') // remove named global scope on SalesMaster

            ->whereBetween('created_at', [$startUtc, $endUtc])
            ->when($customerId && $customerId != 'null', fn ($q) => $q->where('client_id', $customerId))
            ->where('location_id', $location_id)
            ->with([
                'details' => function ($q) {
                    $q->withoutGlobalScope('typeScope')   // remove named global scope on SalesDetails
                        ->where('discount', '>', 0)
                        ->with('salesMaster')
                        ->with(['product', 'arribute']);    // keep your relations
                },
            ])
            ->orderBy('created_at', 'asc')
            ->get();

        // Optional flat details list derived id‑wise from masters
        $details = $masters->flatMap->details->values();
        $masters = $masters->filter(function ($master) {
            return $master->discount > 0;
        })->values();

        return response()->json([
            'date_type' => $endStr ? 'range' : 'single',
            'from' => $startDhaka->toDateString(), // Asia/Dhaka
            'to' => $endDhaka->toDateString(),   // Asia/Dhaka
            'master' => $masters,                    // each master has salesDetails[]
            'details' => $details,                    // optional flat details
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    public function SalesDetalisReport()
    {
        return Inertia::render('Report/SalseDetailsReport');
    }

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

    public function salseReturnReport()
    {
        return Inertia::render('Report/SalseRetutnReport');
    }

    public function salesReturnSearch()
    {

        // 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 = DB::table('sales_return_details_view')
                ->where('location_id', auth()->user()->shop_id)
                ->whereBetween('return_date', [$start, $end])
                ->orderBY('return_date', 'ASC')
                ->get();
        } else {

            $salse = DB::table('sales_return_details_view')->whereDate('return_date', $start)
                ->where('location_id', auth()->user()->shop_id)->get();
        }

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

    public function dueCollection()
    {
        $bank = Bank::get();
        $mobileBank = MobileBanking::get();

        return Inertia::render('Pos/DeuCollection', compact('bank', 'mobileBank'));
    }
}
