<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Shift;
use Illuminate\Http\Request;

class ShiftController extends Controller
{
    /**
     * GET /api/shifts
     */
    public function index(Request $request)
    {
        $shifts = Shift::with('user:id,name')
            ->when($request->user_id, fn($q) => $q->where('user_id', $request->user_id))
            ->when($request->date_from, fn($q) => $q->whereDate('started_at', '>=', $request->date_from))
            ->when($request->date_to,   fn($q) => $q->whereDate('started_at', '<=', $request->date_to))
            ->latest('started_at')
            ->paginate(20);

        return response()->json($shifts->through(fn($s) => $this->format($s)));
    }

    /**
     * POST /api/shifts/open
     */
    public function open(Request $request)
    {
        $user = $request->user();

        // Cek apakah sudah ada shift aktif
        $active = $user->getActiveShift();
        if ($active) {
            return response()->json([
                'message' => 'Shift masih aktif. Tutup shift sebelumnya terlebih dahulu.',
                'shift'   => $this->format($active),
            ], 422);
        }

        $data = $request->validate([
            'notes'          => ['nullable', 'string'],
            'opening_amount' => ['required', 'integer', 'min:0'],
        ]);

        $shift = Shift::create([
            'user_id'        => $user->id,
            'started_at'     => now(),
            'notes'          => $data['notes'] ?? null,
            'opening_amount' => $data['opening_amount'],
        ]);

        return response()->json($this->format($shift->load('user:id,name')), 201);
    }

    /**
     * PATCH /api/shifts/{id}/close
     */
    public function close(Request $request, Shift $shift)
    {
        if ($shift->user_id !== $request->user()->id && !$request->user()->hasRole('super_admin')) {
            return response()->json(['message' => 'Tidak bisa menutup shift orang lain.'], 403);
        }

        if (!is_null($shift->ended_at)) {
            return response()->json(['message' => 'Shift sudah ditutup sebelumnya.'], 422);
        }

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

        $endedAt         = now();
        $durationMinutes = (int) $shift->started_at->diffInMinutes($endedAt);

        $shift->update([
            'ended_at'         => $endedAt,
            'duration_minutes' => $durationMinutes,
            'notes'            => $data['notes'] ?? $shift->notes,
            'closing_amount'   => $data['closing_amount'],
        ]);

        // Hitung ringkasan
        $sales = \App\Models\Sale::where('user_id', $shift->user_id)
            ->whereNull('voided_at')
            ->whereBetween('created_at', [$shift->started_at, $endedAt])
            ->get();

        $cashSales = $sales->where('payment_method', 'cash')->sum('total');
        $expectedCash = $shift->opening_amount + $cashSales;
        $difference = $data['closing_amount'] - $expectedCash;

        $summary = [
            'total_revenue'      => $sales->sum('total'),
            'total_transactions' => $sales->count(),
            'expected_cash'      => $expectedCash,
            'actual_cash'        => $data['closing_amount'],
            'difference'         => $difference,
        ];

        return response()->json([
            'shift'   => $this->format($shift->load('user:id,name')),
            'summary' => $summary,
        ]);
    }

    /**
     * GET /api/shifts/active
     */
    public function active(Request $request)
    {
        $shift = $request->user()->getActiveShift();

        if (!$shift) {
            return response()->json(null);
        }

        return response()->json($this->format($shift->load('user:id,name')));
    }

    /**
     * GET /api/shifts/active/summary
     */
    public function summary(Request $request)
    {
        $shift = $request->user()->getActiveShift();

        if (!$shift) {
            return response()->json(['message' => 'Tidak ada shift aktif'], 404);
        }

        $sales = \App\Models\Sale::where('user_id', $request->user()->id)
            ->whereNull('voided_at')
            ->where('created_at', '>=', $shift->started_at)
            ->get();

        $cashSales = $sales->where('payment_method', 'cash')->sum('total');

        return response()->json([
            'shift' => $this->format($shift->load('user:id,name')),
            'sales' => [
                'count'   => $sales->count(),
                'revenue' => (float) $sales->sum('total'),
                'expected_cash' => $shift->opening_amount + $cashSales,
            ]
        ]);
    }

    private function format(Shift $shift): array
    {
        return [
            'id'               => $shift->id,
            'user_id'          => $shift->user_id,
            'user_name'        => $shift->user?->name ?? 'Unknown',
            'started_at'       => $shift->started_at->toISOString(),
            'ended_at'         => $shift->ended_at?->toISOString(),
            'duration_minutes' => $shift->duration_minutes,
            'notes'            => $shift->notes,
            'opening_amount'   => $shift->opening_amount,
            'closing_amount'   => $shift->closing_amount,
            'total_revenue'    => \App\Models\Sale::where('user_id', $shift->user_id)
                                    ->whereNull('voided_at')
                                    ->whereBetween('created_at', [$shift->started_at, $shift->ended_at ?? now()])
                                    ->sum('total'),
            'total_transactions' => \App\Models\Sale::where('user_id', $shift->user_id)
                                    ->whereNull('voided_at')
                                    ->whereBetween('created_at', [$shift->started_at, $shift->ended_at ?? now()])
                                    ->count(),
            'is_active'        => is_null($shift->ended_at),
        ];
    }
}
