<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\Payment;
use App\Models\Expense;
use Carbon\Carbon;

class DashboardController extends Controller
{
    public function index()
    {
        // Order Counts
        $pending_count = Order::where('status', 0)->count();
        $processing_count = Order::where('status', 1)->count();
        $ready_count = Order::where('status', 2)->count();
        $delivered_count = Order::where('status', 3)->count();
        $returned_count = Order::where('status', 4)->count();

        // Income Calculations
        $today = Carbon::today();
        $currentMonth = Carbon::now()->month;
        $currentYear = Carbon::now()->year;

        $today_income = Payment::whereDate('payment_date', $today)->sum('received_amount');

        $month_gross_income = Payment::whereMonth('payment_date', $currentMonth)
            ->whereYear('payment_date', $currentYear)
            ->sum('received_amount');

        $month_expense = Expense::whereMonth('expense_date', $currentMonth)
            ->whereYear('expense_date', $currentYear)
            ->sum('expense_amount');

        $month_tax = Order::whereMonth('order_date', $currentMonth)
            ->whereYear('order_date', $currentYear)
            ->where('status', 3)
            ->sum('tax_amount');

        $month_net_income = $month_gross_income - $month_expense - $month_tax;
        
        // Recent Orders (Today's Delivery)
        $recent_orders = Order::whereDate('delivery_date', $today->toDateString())
            ->latest()
            ->take(5)
            ->get()
            ->map(function ($order) {
                return [
                    'id' => $order->id,
                    'order_number' => $order->order_number,
                    'customer_name' => $order->customer_name ?? 'Walk In Customer',
                    'status' => $order->status,
                    'delivery_date' => $order->delivery_date,
                    // Add other needed fields
                ];
            });

        return response()->json([
            'success' => true,
            'data' => [
                'counts' => [
                    'pending' => $pending_count,
                    'processing' => $processing_count,
                    'ready' => $ready_count,
                    'delivered' => $delivered_count,
                    'returned' => $returned_count,
                ],
                'income' => [
                    'today' => $today_income,
                    'month_gross' => $month_gross_income,
                    'month_net' => $month_net_income,
                ],
                'recent_orders' => $recent_orders
            ]
        ], 200);
    }
}
