<?php

namespace App\Http\Controllers\Franchise;

use App\Http\Controllers\Controller;
use App\Models\Franchise;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PaymentController extends Controller
{
    public function index(Request $request): View
    {
        $franchise = Franchise::query()->where('created_by', auth()->id())->first();

        $from = (string) $request->input('from', now()->startOfMonth()->toDateString());
        $to = (string) $request->input('to', now()->toDateString());
        $status = (string) $request->input('status', '');
        $gateway = (string) $request->input('gateway', '');

        if (! $franchise) {
            return view('franchise.payments', [
                'franchise' => null,
                'payments' => new LengthAwarePaginator([], 0, 20),
                'summary' => [
                    'gross_sales' => 0,
                    'bv_generated' => 0,
                    'orders' => 0,
                    'cash_sales' => 0,
                    'upi_sales' => 0,
                    'wallet_sales' => 0,
                    'gateway_sales' => 0,
                ],
                'dailySettlement' => collect(),
                'from' => $from,
                'to' => $to,
                'status' => $status,
                'gateway' => $gateway,
            ]);
        }

        $paymentsQuery = DB::table('payment_transactions as pt')
            ->join('orders as o', 'o.id', '=', 'pt.order_id')
            ->leftJoin('users as u', 'u.id', '=', 'o.user_id')
            ->where('o.franchise_id', $franchise->id)
            ->whereDate('pt.created_at', '>=', $from)
            ->whereDate('pt.created_at', '<=', $to);

        if ($status !== '') {
            $paymentsQuery->where('pt.status', $status);
        }

        if ($gateway !== '') {
            $paymentsQuery->where('pt.gateway', $gateway);
        }

        $payments = (clone $paymentsQuery)
            ->select([
                'pt.id',
                'pt.gateway',
                'pt.gateway_transaction_id',
                'pt.amount',
                'pt.status',
                'pt.created_at',
                'o.order_number',
                'o.payment_method',
                'u.member_code',
                'u.name',
            ])
            ->orderByDesc('pt.id')
            ->paginate(20)
            ->withQueryString();

        $settlementBase = DB::table('orders')
            ->where('franchise_id', $franchise->id)
            ->whereIn('status', ['approved', 'delivered', 'dispatched'])
            ->whereDate('approved_at', '>=', $from)
            ->whereDate('approved_at', '<=', $to);

        $summary = [
            'gross_sales' => (float) (clone $settlementBase)->sum('total'),
            'bv_generated' => (float) (clone $settlementBase)->sum('total_bv'),
            'orders' => (int) (clone $settlementBase)->count(),
            'cash_sales' => (float) (clone $settlementBase)->where('payment_method', 'cash')->sum('total'),
            'upi_sales' => (float) (clone $settlementBase)->where('payment_method', 'upi')->sum('total'),
            'wallet_sales' => (float) (clone $settlementBase)->where('payment_method', 'wallet')->sum('total'),
            'gateway_sales' => (float) (clone $settlementBase)->where('payment_method', 'gateway')->sum('total'),
        ];

        $dailySettlement = DB::table('orders')
            ->where('franchise_id', $franchise->id)
            ->whereIn('status', ['approved', 'delivered', 'dispatched'])
            ->whereDate('approved_at', '>=', $from)
            ->whereDate('approved_at', '<=', $to)
            ->selectRaw('DATE(approved_at) as run_date')
            ->selectRaw('COUNT(id) as total_orders')
            ->selectRaw('COALESCE(SUM(total), 0) as total_sales')
            ->selectRaw("COALESCE(SUM(CASE WHEN payment_method = 'cash' THEN total ELSE 0 END), 0) as cash_sales")
            ->selectRaw("COALESCE(SUM(CASE WHEN payment_method = 'upi' THEN total ELSE 0 END), 0) as upi_sales")
            ->selectRaw("COALESCE(SUM(CASE WHEN payment_method = 'wallet' THEN total ELSE 0 END), 0) as wallet_sales")
            ->selectRaw("COALESCE(SUM(CASE WHEN payment_method = 'gateway' THEN total ELSE 0 END), 0) as gateway_sales")
            ->groupBy('run_date')
            ->orderByDesc('run_date')
            ->limit(15)
            ->get();

        return view('franchise.payments', compact(
            'franchise',
            'payments',
            'summary',
            'dailySettlement',
            'from',
            'to',
            'status',
            'gateway'
        ));
    }
}
