<?php

namespace App\Http\Controllers\Franchise;

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

class ProfitAnalyticsController 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());

        if (! $franchise) {
            return view('franchise.profit-analytics', [
                'franchise' => null,
                'from' => $from,
                'to' => $to,
                'summary' => [
                    'gross_sales' => 0,
                    'cogs' => 0,
                    'gross_margin' => 0,
                    'commission_income' => 0,
                    'damage_loss' => 0,
                    'net_profit' => 0,
                ],
                'chartLabels' => [],
                'salesSeries' => [],
                'profitSeries' => [],
            ]);
        }

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

        $grossSales = (float) (clone $salesBase)->sum('total');

        $cogs = (float) DB::table('franchise_transactions')
            ->where('franchise_id', $franchise->id)
            ->where('transaction_type', 'stock_out')
            ->whereDate('transacted_at', '>=', $from)
            ->whereDate('transacted_at', '<=', $to)
            ->sum('amount');

        $commissionIncome = (float) DB::table('franchise_transactions')
            ->where('franchise_id', $franchise->id)
            ->where('transaction_type', 'commission_credit')
            ->whereDate('transacted_at', '>=', $from)
            ->whereDate('transacted_at', '<=', $to)
            ->sum('amount');

        $damageLoss = (float) DB::table('franchise_transactions')
            ->where('franchise_id', $franchise->id)
            ->where('transaction_type', 'damage')
            ->whereDate('transacted_at', '>=', $from)
            ->whereDate('transacted_at', '<=', $to)
            ->sum('amount');

        $grossMargin = round($grossSales - $cogs, 2);
        $netProfit = round($grossMargin + $commissionIncome - $damageLoss, 2);

        $summary = [
            'gross_sales' => $grossSales,
            'cogs' => $cogs,
            'gross_margin' => $grossMargin,
            'commission_income' => $commissionIncome,
            'damage_loss' => $damageLoss,
            'net_profit' => $netProfit,
        ];

        $chartLabels = [];
        $salesSeries = [];
        $profitSeries = [];
        for ($i = 6; $i >= 0; $i--) {
            $date = now()->subDays($i)->toDateString();
            $chartLabels[] = $date;

            $daySales = (float) DB::table('orders')
                ->where('franchise_id', $franchise->id)
                ->whereIn('status', ['approved', 'dispatched', 'delivered'])
                ->whereDate('approved_at', $date)
                ->sum('total');

            $dayCogs = (float) DB::table('franchise_transactions')
                ->where('franchise_id', $franchise->id)
                ->where('transaction_type', 'stock_out')
                ->whereDate('transacted_at', $date)
                ->sum('amount');

            $dayCommission = (float) DB::table('franchise_transactions')
                ->where('franchise_id', $franchise->id)
                ->where('transaction_type', 'commission_credit')
                ->whereDate('transacted_at', $date)
                ->sum('amount');

            $dayDamage = (float) DB::table('franchise_transactions')
                ->where('franchise_id', $franchise->id)
                ->where('transaction_type', 'damage')
                ->whereDate('transacted_at', $date)
                ->sum('amount');

            $salesSeries[] = round($daySales, 2);
            $profitSeries[] = round(($daySales - $dayCogs) + $dayCommission - $dayDamage, 2);
        }

        return view('franchise.profit-analytics', compact(
            'franchise',
            'from',
            'to',
            'summary',
            'chartLabels',
            'salesSeries',
            'profitSeries'
        ));
    }
}

