<?php

namespace App\Http\Controllers\API\V4;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use App\Order; 
use App\Restorant;
use App\Models\OrderHasStatus;
use App\Models\Table;
use Carbon\Carbon;
use Carbon\CarbonPeriod;

class OnlineOrderController extends Controller
{
    public function getTransactionHistory(Request $request)
    {
        $key = $request->get('key'); 
        $firstDate = $request->get('first_date');
        $lastDate = $request->get('last_date');
        $statusInput = $request->get('status');

        // Default to all statuses if empty or "all"
        $statusFilter = (!empty($statusInput) && strtolower($statusInput) !== 'all') ? $statusInput : '';

        // Get user by session key
        $user = User::where('id_session', $key)->first();

        if (!$user) {
            return response()->json([
                'status' => 'true',
                'errCode' => '00',
                'msg' => 'User Not Found'
            ]);
        }

        // Get master user and their store
        $master = User::where('phone_number', $user->master)->first();
        $store = Restorant::where('userz', $master->phone_number)->first();

        $response = [
            'status' => 'true',
            'errCode' => '01',
            'msg' => 'Success',
            'data' => []
        ];

        $period = CarbonPeriod::create($firstDate, $lastDate);

        foreach ($period as $date) {
            $formattedDate = $date->format('Y-m-d');

            // Total order price
            $totalOrder = Order::where('restorant_id', $store->id)
                ->whereDate('date', $formattedDate)
                ->when($statusFilter, fn($q) => $q->where('payment_status', 'LIKE', '%' . $statusFilter . '%'))
                ->sum('order_price');

            // Daily orders
            $orders = Order::where('restorant_id', $store->id)
                ->whereDate('date', $formattedDate)
                ->when($statusFilter, fn($q) => $q->where('payment_status', 'LIKE', '%' . $statusFilter . '%'))
                ->orderBy('id')
                ->get();

            $details = [];

            foreach ($orders as $order) {
                // Get table name
                $table = DbTable::where('id_table', $order->id_table)->first();
                $nameTable = $table ? $table->name_table : '-';

                // Get order status
                $latestStatus = OrderHasStatus::where('order_id', $order->id)
                    ->orderByDesc('id')
                    ->first();

                $statusOrder = match ($latestStatus->status_id ?? null) {
                    '1' => 'Pending',
                    '2', '3' => 'In Progress',
                    '5', '7' => 'Delivered',
                    '9' => 'Returned',
                    '11' => 'Cancel',
                    default => 'Pending',
                };

                $details[] = [
                    'id_customer' => $order->id,
                    'no_invoice' => $order->no_invoice,
                    'date' => $order->date,
                    'payment' => $order->payment_method,
                    'totalorder' => $order->order_price,
                    'totalpay' => $order->delivery_price,
                    'changepay' => $order->delivery_price,
                    'status' => $order->payment_status,
                    'statusorder' => $statusOrder,
                    'name_table' => $nameTable
                ];
            }

            $response['data'][] = [
                'totalorderall' => $totalOrder ?? 0,
                'date' => $formattedDate,
                'detail' => $details
            ];
        }

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