<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Activity;
use App\Models\Attendance;
use App\Services\ActivityService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ActivityController extends Controller
{
    public function __construct(
        private ActivityService $activityService
    ) {}

    /**
     * Mendapatkan aktivitas harian
     */
    public function index(Request $request): JsonResponse
    {
        $request->validate([
            'date' => 'required|date',
        ]);

        $result = $this->activityService->getByDate(
            user: $request->user(),
            date: $request->date
        );

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

    /**
     * Membuat aktivitas baru
     */
    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'date' => 'required|date',
            'start_time' => 'required|date_format:H:i',
            'end_time' => 'required|date_format:H:i',
            'activity' => 'required|string',
            'output' => 'nullable|string',
            'notes' => 'nullable|string',
        ]);

        $result = $this->activityService->create(
            user: $request->user(),
            date: $request->date,
            startTime: $request->start_time,
            endTime: $request->end_time,
            activity: $request->activity,
            output: $request->output,
            notes: $request->notes
        );

        return response()->json($result, $result['success'] ? 201 : 400);
    }

    /**
     * Update aktivitas
     */
    public function update(Request $request, Activity $activity): JsonResponse
    {
        // Pastikan aktivitas milik user yang login
        if ($activity->user_id !== $request->user()->id) {
            return response()->json([
                'success' => false,
                'message' => 'Aktivitas tidak ditemukan',
            ], 404);
        }

        $request->validate([
            'start_time' => 'required|date_format:H:i',
            'end_time' => 'required|date_format:H:i',
            'activity' => 'required|string',
            'output' => 'nullable|string',
            'notes' => 'nullable|string',
        ]);

        $result = $this->activityService->update(
            activity: $activity,
            startTime: $request->start_time,
            endTime: $request->end_time,
            activityText: $request->activity,
            output: $request->output,
            notes: $request->notes
        );

        return response()->json($result, $result['success'] ? 200 : 400);
    }

    /**
     * Cek apakah activity bisa dibuat untuk tanggal tertentu
     * Returns status attendance dan info untuk UI
     */
    public function canCreate(Request $request): JsonResponse
    {
        $request->validate([
            'date' => 'required|date',
        ]);

        $user = $request->user();
        $date = $request->date;

        // Cek attendance pada tanggal tersebut
        $attendance = Attendance::where('user_id', $user->id)
            ->whereDate('date', $date)
            ->first();

        // Tidak ada attendance
        if (!$attendance) {
            return response()->json([
                'success' => true,
                'can_create' => false,
                'reason' => 'no_attendance',
                'message' => 'Tidak ada presensi pada tanggal ini. Silakan check-in terlebih dahulu.',
                'attendance' => null,
            ]);
        }

        // Ada attendance tapi belum check-in (seharusnya tidak terjadi, tapi handle)
        if (!$attendance->check_in_time) {
            return response()->json([
                'success' => true,
                'can_create' => false,
                'reason' => 'no_checkin',
                'message' => 'Belum ada check-in pada tanggal ini. Silakan check-in terlebih dahulu.',
                'attendance' => $attendance,
            ]);
        }

        // Attendance dengan check-in ada, bisa buat activity
        return response()->json([
            'success' => true,
            'can_create' => true,
            'reason' => null,
            'message' => 'Aktivitas dapat dibuat',
            'attendance' => $attendance->load(['company']),
            'time_range' => [
                'min_time' => $attendance->check_in_time ? \Carbon\Carbon::parse($attendance->check_in_time)->format('H:i') : '08:00',
                'max_time' => $attendance->check_out_time ? \Carbon\Carbon::parse($attendance->check_out_time)->format('H:i') : '17:00',
            ],
        ]);
    }

    /**
     * Membuat aktivitas dari attendance ID (integrated approach)
     */
    public function storeFromAttendance(Request $request, Attendance $attendance): JsonResponse
    {
        // Pastikan attendance milik user yang login
        if ($attendance->user_id !== $request->user()->id) {
            return response()->json([
                'success' => false,
                'message' => 'Presensi tidak ditemukan',
            ], 404);
        }

        $request->validate([
            'start_time' => 'required|date_format:H:i',
            'end_time' => 'required|date_format:H:i',
            'activity' => 'required|string',
            'output' => 'nullable|string',
            'notes' => 'nullable|string',
        ]);

        $result = $this->activityService->create(
            user: $request->user(),
            date: $attendance->date->format('Y-m-d'),
            startTime: $request->start_time,
            endTime: $request->end_time,
            activity: $request->activity,
            output: $request->output,
            notes: $request->notes
        );

        return response()->json($result, $result['success'] ? 201 : 400);
    }
}
