<?php

namespace App\Http\Controllers\Api;

use App\Models\Activity;
use App\Models\Tenant;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;

class ActivityController extends Controller
{
    /**
     * Get all activities for the current tenant
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $user = auth('api')->user();
            if (!$user) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized'
                ], 401);
            }

            $tenantId = $user->tenant_id;

            // Get query parameters for filtering
            $type = $request->query('type');
            $status = $request->query('status');
            $priority = $request->query('priority');

            $query = Activity::where('tenant_id', $tenantId)
                ->orderBy('created_at', 'desc');

            if ($type) {
                $query->where('type', $type);
            }
            if ($status) {
                $query->where('status', $status);
            }
            if ($priority) {
                $query->where('priority', $priority);
            }

            $activities = $query->get();

            return response()->json([
                'success' => true,
                'data' => $activities,
                'count' => $activities->count()
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error fetching activities',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Create a new activity
     */
    public function store(Request $request): JsonResponse
    {
        try {
            $user = auth('api')->user();
            if (!$user) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized'
                ], 401);
            }

            $validated = $request->validate([
                'customer_name' => 'required|string|max:255',
                'customer_id' => 'nullable|exists:users,id',
                'type' => 'required|in:note,follow_up,task,reminder,resolution',
                'title' => 'required|string|max:500',
                'content' => 'required|string',
                'priority' => 'required|in:low,medium,high',
                'due_date' => 'nullable|date_format:Y-m-d\TH:i',
                'status' => 'required|in:open,in_progress,completed',
                'tags' => 'nullable|json'
            ]);

            $activity = Activity::create([
                'tenant_id' => $user->tenant_id,
                'customer_id' => $validated['customer_id'] ?? null,
                'customer_name' => $validated['customer_name'],
                'type' => $validated['type'],
                'title' => $validated['title'],
                'content' => $validated['content'],
                'priority' => $validated['priority'],
                'due_date' => $validated['due_date'] ?? null,
                'status' => $validated['status'],
                'tags' => $validated['tags'] ? json_decode($validated['tags'], true) : null,
                'created_by' => $user->id
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Activity created successfully',
                'data' => $activity
            ], 201);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error creating activity',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get a single activity
     */
    public function show(string $id): JsonResponse
    {
        try {
            $user = auth('api')->user();
            if (!$user) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized'
                ], 401);
            }

            $activity = Activity::where('id', $id)
                ->where('tenant_id', $user->tenant_id)
                ->firstOrFail();

            return response()->json([
                'success' => true,
                'data' => $activity
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Activity not found'
            ], 404);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error fetching activity',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Update an activity
     */
    public function update(Request $request, string $id): JsonResponse
    {
        try {
            $user = auth('api')->user();
            if (!$user) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized'
                ], 401);
            }

            $activity = Activity::where('id', $id)
                ->where('tenant_id', $user->tenant_id)
                ->firstOrFail();

            $validated = $request->validate([
                'customer_name' => 'sometimes|string|max:255',
                'customer_id' => 'nullable|exists:users,id',
                'type' => 'sometimes|in:note,follow_up,task,reminder,resolution',
                'title' => 'sometimes|string|max:500',
                'content' => 'sometimes|string',
                'priority' => 'sometimes|in:low,medium,high',
                'due_date' => 'nullable|date_format:Y-m-d\TH:i',
                'status' => 'sometimes|in:open,in_progress,completed',
                'tags' => 'nullable|json'
            ]);

            if (isset($validated['tags']) && $validated['tags']) {
                $validated['tags'] = json_decode($validated['tags'], true);
            }

            $activity->update($validated);

            return response()->json([
                'success' => true,
                'message' => 'Activity updated successfully',
                'data' => $activity
            ]);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Activity not found'
            ], 404);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error updating activity',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Delete an activity
     */
    public function destroy(string $id): JsonResponse
    {
        try {
            $user = auth('api')->user();
            if (!$user) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized'
                ], 401);
            }

            $activity = Activity::where('id', $id)
                ->where('tenant_id', $user->tenant_id)
                ->firstOrFail();

            $activity->delete();

            return response()->json([
                'success' => true,
                'message' => 'Activity deleted successfully'
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Activity not found'
            ], 404);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error deleting activity',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
