<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Shift;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ShiftController extends Controller
{
    /**
     * Open a new shift with opening balance
     */
    public function openShift(Request $request)
    {
        $request->validate([
            'branch_id' => 'required|exists:branches,id',
            'shift_date' => 'required|date',
            'opening_balance' => 'required|numeric|min:0',
            'notes' => 'nullable|string',
        ]);

        $user = $request->user();
        $restaurantId = $request->input('restaurant_id') ?? $user->restaurant_id ?? $user->branch?->restaurant_id;

        if (!$restaurantId) {
            return response()->json([
                'message' => 'Restaurant ID is required'
            ], 400);
        }

        // Check if there's already an open shift for this branch
        $existingShift = Shift::where('branch_id', $request->branch_id)
            ->where('status', 'open')
            ->first();

        if ($existingShift) {
            return response()->json([
                'message' => 'There is already an open shift for this branch. Please close it first.',
                'shift' => $existingShift
            ], 400);
        }

        $shift = Shift::create([
            'restaurant_id' => $restaurantId,
            'branch_id' => $request->branch_id,
            'user_id' => $user->id,
            'shift_date' => $request->shift_date,
            'start_time' => now(),
            'opening_balance' => $request->opening_balance,
            'status' => 'open',
            'notes' => $request->notes,
        ]);

        return response()->json([
            'message' => 'Shift opened successfully',
            'shift' => $shift->load(['restaurant', 'branch', 'user'])
        ], 201);
    }

    /**
     * Close a shift with closing balance
     */
    public function closeShift(Request $request, Shift $shift)
    {
        $request->validate([
            'closing_balance' => 'required|numeric|min:0',
            'notes' => 'nullable|string',
        ]);

        $user = $request->user();

        // Verify shift belongs to user's restaurant/branch
        if ($user->isRestaurantOwner() && $shift->restaurant_id !== $user->restaurant_id) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        if ($user->isBranchManager() && $shift->branch_id !== $user->branch_id) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        if ($shift->status === 'closed') {
            return response()->json([
                'message' => 'Shift is already closed'
            ], 400);
        }

        $shift->update([
            'end_time' => now(),
            'closing_balance' => $request->closing_balance,
            'status' => 'closed',
            'notes' => $request->notes ?? $shift->notes,
        ]);

        return response()->json([
            'message' => 'Shift closed successfully',
            'shift' => $shift->load(['restaurant', 'branch', 'user', 'dailyExpenses'])
        ]);
    }

    /**
     * Get current open shift
     */
    public function getCurrentShift(Request $request)
    {
        $user = $request->user();
        $branchId = $request->input('branch_id') 
            ?? session('selected_branch_id')
            ?? $user->branch_id;

        if (!$branchId) {
            return response()->json([
                'message' => 'Branch ID is required'
            ], 400);
        }

        $shift = Shift::where('branch_id', $branchId)
            ->where('status', 'open')
            ->with(['restaurant', 'branch', 'user', 'dailyExpenses'])
            ->first();

        if (!$shift) {
            return response()->json([
                'shift' => null,
                'message' => 'No open shift found'
            ]);
        }

        return response()->json([
            'shift' => $shift
        ]);
    }

    /**
     * List shifts
     */
    public function index(Request $request)
    {
        $user = $request->user();
        $query = Shift::query();

        // Filter by restaurant
        if ($user->isRestaurantOwner() && $user->restaurant_id) {
            $query->where('restaurant_id', $user->restaurant_id);
        } elseif ($user->isBranchManager() && $user->branch_id) {
            $query->where('branch_id', $user->branch_id);
        } elseif ($user->branch_id) {
            $query->where('branch_id', $user->branch_id);
        }

        // Filter by branch if provided
        if ($request->has('branch_id')) {
            $query->where('branch_id', $request->branch_id);
        }

        // Filter by date range
        if ($request->has('start_date')) {
            $query->where('shift_date', '>=', $request->start_date);
        }
        if ($request->has('end_date')) {
            $query->where('shift_date', '<=', $request->end_date);
        }

        // Filter by status
        if ($request->has('status')) {
            $query->where('status', $request->status);
        }

        $shifts = $query->with(['restaurant', 'branch', 'user'])
            ->orderBy('shift_date', 'desc')
            ->orderBy('created_at', 'desc')
            ->paginate($request->get('per_page', 15));

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