<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Interaction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class InteractionController extends Controller
{
    /**
     * Get all interactions with optional filtering
     */
    public function index(Request $request)
    {
        try {
            $user = auth('api')->user();
            
            // Get the user's tenant
            $tenantId = $user && isset($user->tenant_id) ? $user->tenant_id : null;
            
            if (!$tenantId) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tenant ID not found',
                ], 401);
            }

            $query = Interaction::byTenant($tenantId);

            // Filter by customer_id if provided
            if ($customerId = $request->query('customer_id')) {
                $query->where('customer_id', $customerId);
            }

            // Filter by status if provided
            if ($status = $request->query('status')) {
                $query->byStatus($status);
            }

            // Filter by priority if provided
            if ($priority = $request->query('priority')) {
                $query->byPriority($priority);
            }

            // Filter by type if provided
            if ($type = $request->query('type')) {
                $query->byType($type);
            }

            // Search by subject or notes
            if ($search = $request->query('search')) {
                $query->where(function ($q) use ($search) {
                    $q->where('subject', 'like', "%{$search}%")
                      ->orWhere('notes', 'like', "%{$search}%")
                      ->orWhere('customer_name', 'like', "%{$search}%");
                });
            }

            $interactions = $query->orderBy('interaction_date', 'desc')
                                  ->orderBy('created_at', 'desc')
                                  ->get();

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

    /**
     * Store a new interaction
     */
    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'customer_id' => 'required|exists:customers,id',
                'customer_name' => 'required|string|max:255',
                'type' => 'required|in:call,message,email,in_app,support_ticket',
                'subject' => 'required|string|max:255',
                'status' => 'required|in:pending,completed,follow_up_needed',
                'priority' => 'required|in:low,medium,high',
                'notes' => 'nullable|string',
                'resolution' => 'nullable|string',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors(),
                ], 422);
            }

            $user = auth('api')->user();
            $tenantId = $user && isset($user->tenant_id) ? $user->tenant_id : null;

            if (!$tenantId) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tenant ID not found',
                ], 401);
            }

            $interaction = Interaction::create([
                'tenant_id' => $tenantId,
                'customer_id' => $request->input('customer_id'),
                'customer_name' => $request->input('customer_name'),
                'type' => $request->input('type'),
                'subject' => $request->input('subject'),
                'status' => $request->input('status'),
                'priority' => $request->input('priority'),
                'notes' => $request->input('notes'),
                'resolution' => $request->input('resolution'),
                'interaction_date' => now(),
                'created_by' => $user->id,
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Interaction created successfully',
                'data' => $interaction,
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error creating interaction',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Get a single interaction
     */
    public function show($id)
    {
        try {
            $user = auth('api')->user();
            $tenantId = $user && isset($user->tenant_id) ? $user->tenant_id : null;

            if (!$tenantId) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tenant ID not found',
                ], 401);
            }

            $interaction = Interaction::where('tenant_id', $tenantId)
                                      ->findOrFail($id);

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

    /**
     * Update an interaction
     */
    public function update(Request $request, $id)
    {
        try {
            $validator = Validator::make($request->all(), [
                'customer_id' => 'nullable|exists:customers,id',
                'customer_name' => 'nullable|string|max:255',
                'type' => 'nullable|in:call,message,email,in_app,support_ticket',
                'subject' => 'nullable|string|max:255',
                'status' => 'nullable|in:pending,completed,follow_up_needed',
                'priority' => 'nullable|in:low,medium,high',
                'notes' => 'nullable|string',
                'resolution' => 'nullable|string',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors(),
                ], 422);
            }

            $user = auth('api')->user();
            $tenantId = $user && isset($user->tenant_id) ? $user->tenant_id : null;

            if (!$tenantId) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tenant ID not found',
                ], 401);
            }

            $interaction = Interaction::where('tenant_id', $tenantId)
                                      ->findOrFail($id);

            $updateData = [];
            if ($request->has('customer_id')) $updateData['customer_id'] = $request->input('customer_id');
            if ($request->has('customer_name')) $updateData['customer_name'] = $request->input('customer_name');
            if ($request->has('type')) $updateData['type'] = $request->input('type');
            if ($request->has('subject')) $updateData['subject'] = $request->input('subject');
            if ($request->has('status')) $updateData['status'] = $request->input('status');
            if ($request->has('priority')) $updateData['priority'] = $request->input('priority');
            if ($request->has('notes')) $updateData['notes'] = $request->input('notes');
            if ($request->has('resolution')) $updateData['resolution'] = $request->input('resolution');

            $interaction->update($updateData);

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

    /**
     * Delete an interaction
     */
    public function destroy($id)
    {
        try {
            $user = auth('api')->user();
            $tenantId = $user && isset($user->tenant_id) ? $user->tenant_id : null;

            if (!$tenantId) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tenant ID not found',
                ], 401);
            }

            $interaction = Interaction::where('tenant_id', $tenantId)
                                      ->findOrFail($id);

            $interaction->delete();

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