<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\EmployeeAttendance;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class EmployeeAttendanceController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:sanctum');
    }

    /**
     * Get all employee attendances
     */
    public function index(Request $request)
    {
        $user = $request->user();
        
        if (!$user || !in_array($user->role, ['admin', 'restaurant_owner', 'branch_manager'])) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $query = EmployeeAttendance::with(['employee', 'branch', 'restaurant']);

        // Apply role-based filtering
        if ($user->role === 'admin') {
            if ($request->has('restaurant_id') && $request->restaurant_id) {
                $query->where('restaurant_id', $request->restaurant_id);
            }
            if ($request->has('branch_id') && $request->branch_id) {
                $query->where('branch_id', $request->branch_id);
            }
        } elseif ($user->role === 'restaurant_owner') {
            $query->where('restaurant_id', $user->restaurant_id);
            if ($request->has('branch_id') && $request->branch_id) {
                $query->where('branch_id', $request->branch_id);
            }
        } elseif ($user->role === 'branch_manager') {
            $query->where('restaurant_id', $user->restaurant_id)
                  ->where('branch_id', $user->branch_id);
        }

        // Date filter
        if ($request->has('date_from')) {
            $query->where('date', '>=', $request->date_from);
        }
        if ($request->has('date_to')) {
            $query->where('date', '<=', $request->date_to);
        }

        // Search functionality
        if ($request->has('search') && $request->search) {
            $search = $request->search;
            $query->whereHas('employee', function($q) use ($search) {
                $q->where('name', 'like', '%' . $search . '%')
                  ->orWhere('email', 'like', '%' . $search . '%');
            });
        }

        $attendances = $query->orderBy('date', 'desc')->get();

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

    /**
     * Create new employee attendance
     */
    public function store(Request $request)
    {
        $user = $request->user();
        
        if (!$user || !in_array($user->role, ['admin', 'restaurant_owner', 'branch_manager'])) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $validated = $request->validate([
            'employee_id' => 'required|exists:users,id',
            'date' => 'required|date',
            'check_in' => 'nullable|date_format:H:i',
            'check_out' => 'nullable|date_format:H:i|after:check_in',
            'status' => ['required', Rule::in(['present', 'absent', 'late', 'half_day', 'leave'])],
            'notes' => 'nullable|string',
        ]);

        // Get employee to determine restaurant_id and branch_id
        $employee = User::findOrFail($validated['employee_id']);

        // Check access
        if ($user->role === 'restaurant_owner' && $employee->restaurant_id !== $user->restaurant_id) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }
        if ($user->role === 'branch_manager' && $employee->branch_id !== $user->branch_id) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        // Check if attendance already exists for this employee and date
        $existing = EmployeeAttendance::where('employee_id', $validated['employee_id'])
            ->where('date', $validated['date'])
            ->first();

        if ($existing) {
            return response()->json(['error' => 'Attendance record already exists for this date'], 422);
        }

        $attendance = EmployeeAttendance::create([
            'employee_id' => $validated['employee_id'],
            'date' => $validated['date'],
            'check_in' => $validated['check_in'] ?? null,
            'check_out' => $validated['check_out'] ?? null,
            'status' => $validated['status'],
            'notes' => $validated['notes'] ?? null,
            'restaurant_id' => $employee->restaurant_id,
            'branch_id' => $employee->branch_id,
        ]);

        $attendance->load(['employee', 'branch', 'restaurant']);

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

    /**
     * Update employee attendance
     */
    public function update(Request $request, $id)
    {
        $user = $request->user();
        
        if (!$user || !in_array($user->role, ['admin', 'restaurant_owner', 'branch_manager'])) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $attendance = EmployeeAttendance::findOrFail($id);

        // Check access
        if ($user->role === 'restaurant_owner' && $attendance->restaurant_id !== $user->restaurant_id) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }
        if ($user->role === 'branch_manager' && $attendance->branch_id !== $user->branch_id) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $validated = $request->validate([
            'employee_id' => 'sometimes|required|exists:users,id',
            'date' => 'sometimes|required|date',
            'check_in' => 'nullable|date_format:H:i',
            'check_out' => 'nullable|date_format:H:i|after:check_in',
            'status' => ['sometimes', 'required', Rule::in(['present', 'absent', 'late', 'half_day', 'leave'])],
            'notes' => 'nullable|string',
        ]);

        // If date or employee_id changed, check for duplicates
        if (isset($validated['date']) || isset($validated['employee_id'])) {
            $employeeId = $validated['employee_id'] ?? $attendance->employee_id;
            $date = $validated['date'] ?? $attendance->date;
            
            $existing = EmployeeAttendance::where('employee_id', $employeeId)
                ->where('date', $date)
                ->where('id', '!=', $id)
                ->first();

            if ($existing) {
                return response()->json(['error' => 'Attendance record already exists for this date'], 422);
            }
        }

        $attendance->update($validated);
        $attendance->load(['employee', 'branch', 'restaurant']);

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

    /**
     * Delete employee attendance
     */
    public function destroy($id)
    {
        $user = request()->user();
        
        if (!$user || !in_array($user->role, ['admin', 'restaurant_owner', 'branch_manager'])) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $attendance = EmployeeAttendance::findOrFail($id);

        // Check access
        if ($user->role === 'restaurant_owner' && $attendance->restaurant_id !== $user->restaurant_id) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }
        if ($user->role === 'branch_manager' && $attendance->branch_id !== $user->branch_id) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $attendance->delete();

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