<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\CashRegister;
use App\Models\Sale;
use App\Models\SalePayment;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class CashRegisterController extends Controller
{
    public function status(): JsonResponse
    {
        $user = Auth::user();
        
        $openCashRegister = CashRegister::where('user_id', $user->id)
            ->where('status', 'open')
            ->orderBy('opening_time', 'desc')
            ->first();

        if (!$openCashRegister) {
            return response()->json([
                'is_open' => false,
                'cash_register' => null
            ]);
        }

        $completedSalesByMethod = SalePayment::whereHas('sale', function ($query) use ($openCashRegister) {
                $query->where('cash_register_id', $openCashRegister->id)
                      ->where('status', 'completed');
            })
            ->select('payment_method')
            ->selectRaw('SUM(amount) as total')
            ->groupBy('payment_method')
            ->get()
            ->pluck('total', 'payment_method')
            ->toArray();

        $salesCount = Sale::where('cash_register_id', $openCashRegister->id)
            ->whereIn('status', ['pending', 'completed'])
            ->count();

        $completedSalesTotal = Sale::where('cash_register_id', $openCashRegister->id)
            ->where('status', 'completed')
            ->sum('total');

        return response()->json([
            'is_open' => true,
            'cash_register' => $openCashRegister,
            'sales_count' => $salesCount,
            'completed_sales_total' => $completedSalesTotal,
            'completed_sales_by_method' => $completedSalesByMethod
        ]);
    }

    public function open(Request $request): JsonResponse
    {
        $user = Auth::user();

        $openCashRegister = CashRegister::where('user_id', $user->id)
            ->where('status', 'open')
            ->first();

        if ($openCashRegister) {
            return response()->json(['error' => 'Ya tienes una caja abierta'], 400);
        }

        $validated = $request->validate([
            'opening_amount' => 'required|numeric|min:0',
            'notes' => 'nullable|string',
            'hostname' => 'nullable|string|max:100',
            'mac_address' => 'nullable|string|max:50',
        ]);

        $cashRegister = CashRegister::create([
            'user_id' => $user->id,
            'opening_amount' => $validated['opening_amount'],
            'opening_time' => Carbon::now(),
            'status' => 'open',
            'notes' => $validated['notes'] ?? null,
            'hostname' => $validated['hostname'] ?? null,
            'mac_address' => $validated['mac_address'] ?? null,
        ]);

        return response()->json($cashRegister, 201);
    }

    public function close(Request $request): JsonResponse
    {
        $user = Auth::user();

        $cashRegister = CashRegister::where('user_id', $user->id)
            ->where('status', 'open')
            ->orderBy('opening_time', 'desc')
            ->first();

        if (!$cashRegister) {
            return response()->json(['error' => 'No tienes una caja abierta'], 400);
        }

        $validated = $request->validate([
            'closing_amount' => 'required|numeric|min:0',
            'notes' => 'nullable|string',
        ]);

        $completedSalesTotal = Sale::where('cash_register_id', $cashRegister->id)
            ->where('status', 'completed')
            ->sum('total');

        $salesByMethod = Sale::where('cash_register_id', $cashRegister->id)
            ->where('status', 'completed')
            ->select('payment_method')
            ->selectRaw('SUM(total) as total')
            ->groupBy('payment_method')
            ->get()
            ->pluck('total', 'payment_method')
            ->toArray();

        $expectedAmount = $cashRegister->opening_amount + $completedSalesTotal;
        $difference = $validated['closing_amount'] - $expectedAmount;

        $cashRegister->update([
            'closing_amount' => $validated['closing_amount'],
            'expected_amount' => $expectedAmount,
            'difference' => $difference,
            'closing_time' => Carbon::now(),
            'status' => 'closed',
            'notes' => $validated['notes'] ?? $cashRegister->notes,
        ]);

        $salesCount = Sale::where('cash_register_id', $cashRegister->id)
            ->where('status', 'completed')
            ->count();

        return response()->json([
            'cash_register' => $cashRegister->fresh(),
            'sales_total' => $completedSalesTotal,
            'sales_count' => $salesCount,
            'sales_by_method' => $salesByMethod
        ]);
    }

    public function history(): JsonResponse
    {
        $user = Auth::user();
        
        $cashRegisters = CashRegister::where('user_id', $user->id)
            ->orderBy('created_at', 'desc')
            ->limit(30)
            ->get();

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

    public function allHistory(): JsonResponse
    {
        $cashRegisters = CashRegister::with('user')
            ->orderBy('created_at', 'desc')
            ->limit(50)
            ->get();

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