<?php

namespace App\Http\Controllers\Api;

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

class DailyExpenseController extends Controller
{
    /**
     * List daily expenses
     */
    public function index(Request $request)
    {
        $user = $request->user();
        $query = DailyExpense::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 shift if provided
        if ($request->has('shift_id')) {
            $query->where('shift_id', $request->shift_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('expense_date', '>=', $request->start_date);
        }
        if ($request->has('end_date')) {
            $query->where('expense_date', '<=', $request->end_date);
        }

        $expenses = $query->with(['restaurant', 'branch', 'shift', 'creator'])
            ->orderBy('expense_date', 'desc')
            ->orderBy('created_at', 'desc')
            ->paginate($request->get('per_page', 15));

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

    /**
     * Store a new daily expense
     */
    public function store(Request $request)
    {
        $request->validate([
            'shift_id' => 'nullable|exists:shifts,id',
            'branch_id' => 'required|exists:branches,id',
            'expense_category' => 'required|string|max:255',
            'description' => 'nullable|string',
            'amount' => 'required|numeric|min:0',
            'expense_date' => 'required|date',
            '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);
        }

        // Verify shift belongs to branch if provided
        if ($request->shift_id) {
            $shift = Shift::find($request->shift_id);
            if ($shift && $shift->branch_id !== $request->branch_id) {
                return response()->json([
                    'message' => 'Shift does not belong to the specified branch'
                ], 400);
            }
        }

        $expense = DailyExpense::create([
            'shift_id' => $request->shift_id,
            'restaurant_id' => $restaurantId,
            'branch_id' => $request->branch_id,
            'expense_category' => $request->expense_category,
            'description' => $request->description,
            'amount' => $request->amount,
            'expense_date' => $request->expense_date,
            'created_by' => $user->id,
            'notes' => $request->notes,
        ]);

        return response()->json([
            'message' => 'Daily expense created successfully',
            'expense' => $expense->load(['restaurant', 'branch', 'shift', 'creator'])
        ], 201);
    }

    /**
     * Update a daily expense
     */
    public function update(Request $request, DailyExpense $dailyExpense)
    {
        $user = $request->user();

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

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

        $request->validate([
            'expense_category' => 'sometimes|string|max:255',
            'description' => 'nullable|string',
            'amount' => 'sometimes|numeric|min:0',
            'expense_date' => 'sometimes|date',
            'notes' => 'nullable|string',
        ]);

        $dailyExpense->update($request->only([
            'expense_category',
            'description',
            'amount',
            'expense_date',
            'notes',
        ]));

        return response()->json([
            'message' => 'Daily expense updated successfully',
            'expense' => $dailyExpense->load(['restaurant', 'branch', 'shift', 'creator'])
        ]);
    }

    /**
     * Delete a daily expense
     */
    public function destroy(DailyExpense $dailyExpense)
    {
        $user = request()->user();

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

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

        $dailyExpense->delete();

        return response()->json([
            'message' => 'Daily expense deleted successfully'
        ]);
    }

    /**
     * Show a single daily expense
     */
    public function show(DailyExpense $dailyExpense)
    {
        $user = request()->user();

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

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

        return response()->json([
            'expense' => $dailyExpense->load(['restaurant', 'branch', 'shift', 'creator'])
        ]);
    }
}
