<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\Production;
use App\Models\ResellerBarter;
use App\Models\ResellerPaymentHistory;
use Carbon\Carbon;

class ReportController extends Controller
{
    public function index(Request $request)
    {
        $endDate   = $request->end_date
            ? Carbon::parse($request->end_date)
            : Carbon::now();

        $startDate = $request->start_date
            ? Carbon::parse($request->start_date)
            : Carbon::now()->subMonths(3);

        $weeks = [];

        $start = $startDate->copy()->startOfWeek(Carbon::MONDAY);
        $end   = $endDate->copy()->endOfWeek(Carbon::SUNDAY);

        while ($start <= $end) {

            $weekStart = $start->copy();
            $weekEnd   = $start->copy()->endOfWeek(Carbon::SUNDAY);

            $totalPenjualan = Order::whereBetween('order_date', [$weekStart, $weekEnd])
                ->where('status', 'completed')
                ->sum('total_price');

            $totalReseller = ResellerPaymentHistory::whereBetween('payment_date', [$weekStart, $weekEnd])
                ->sum('amount');

            $barters = ResellerBarter::with('product')
                ->whereBetween('date', [$weekStart, $weekEnd])
                ->get();

            $totalBarter = $barters->sum(function ($b) {
                return $b->product->reseller_price * $b->qty;
            });

            $productions = Production::whereBetween('production_date', [$weekStart, $weekEnd])->get();

            $biayaOperasional = $productions->sum('operational_cost');
            $biayaBahan       = $productions->sum('cost_material');
            $totalBiaya       = $biayaOperasional + $biayaBahan;

            $labaBersih = ($totalPenjualan + $totalReseller) - $totalBarter - $totalBiaya;

            $weeks[] = [
                'tanggal_awal_raw'  => $weekStart->format('Y-m-d'),
                'tanggal_akhir_raw' => $weekEnd->format('Y-m-d'),
                'tanggal_awal'      => $weekStart->translatedFormat('d F Y'),
                'tanggal_akhir'     => $weekEnd->translatedFormat('d F Y'),
                'total_penjualan'   => $totalPenjualan,
                'total_reseller'    => $totalReseller,
                'total_barter'      => $totalBarter,
                'biaya_bahan'       => $biayaBahan,
                'biaya_operasional' => $biayaOperasional,
                'total_biaya'       => $totalBiaya,
                'laba_bersih'       => $labaBersih,
            ];

            $start->addWeek();
        }

        $weeks = array_reverse($weeks);

        return view('reports.index', [
            'weeks'     => $weeks,
            'startDate' => $startDate->format('Y-m-d'),
            'endDate'   => $endDate->format('Y-m-d'),
        ]);
    }

    public function monthly(Request $request)
    {
        $year = $request->year ?? Carbon::now()->year;

        $start = Carbon::create($year, 1, 1)->startOfMonth();
        $end   = Carbon::create($year, 12, 1)->endOfMonth();

        $months = [];

        while ($start <= $end) {

            $monthStart = $start->copy()->startOfMonth();
            $monthEnd   = $start->copy()->endOfMonth();

            $totalPenjualan = Order::whereBetween('order_date', [$monthStart, $monthEnd])
                ->where('status', 'completed')
                ->sum('total_price');

            $totalReseller = ResellerPaymentHistory::whereBetween('payment_date', [$monthStart, $monthEnd])
                ->sum('amount');

            $barters = ResellerBarter::with('product')
                ->whereBetween('date', [$monthStart, $monthEnd])
                ->get();

            $totalBarter = $barters->sum(fn($b) =>
                $b->product->reseller_price * $b->qty
            );

            $productions = Production::whereBetween('production_date', [$monthStart, $monthEnd])->get();

            $biayaOperasional = $productions->sum('operational_cost');
            $biayaBahan       = $productions->sum('cost_material');
            $totalBiaya       = $biayaOperasional + $biayaBahan;

            $labaBersih = ($totalPenjualan + $totalReseller) - $totalBarter - $totalBiaya;

            $months[] = [
                'bulan'             => $monthStart->translatedFormat('F Y'),
                'total_penjualan'   => $totalPenjualan,
                'total_reseller'    => $totalReseller,
                'total_barter'      => $totalBarter,
                'biaya_bahan'       => $biayaBahan,
                'biaya_operasional' => $biayaOperasional,
                'total_biaya'       => $totalBiaya,
                'laba_bersih'       => $labaBersih,
            ];

            $start->addMonth();
        }

        return view('reports.monthly', [
            'months' => $months,
            'year'   => $year
        ]);
    }
}
