<?php

namespace App\Modules\ThreeCX\Controllers;

use App\Http\Controllers\BaseController;
use App\Models\Call;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

/**
 * Calls REST API Controller for ThreeCX Module
 * 
 * Handles API endpoints for call management within the ThreeCX module
 */
class CallsControllerREST extends BaseController
{
    /**
     * Get call history for a client
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function history(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'client_id' => 'required|integer',
            'client_type' => 'string|in:client,customer,task',
            'limit' => 'integer|min:1|max:100'
        ]);

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

        try {
            $clientId = $request->client_id;
            $clientType = $request->client_type ?? 'client';
            $limit = $request->limit ?? 50;

            $calls = Call::forClient($clientId, $clientType)
                ->with(['user:id,first_name,last_name'])
                ->orderBy('created_at', 'desc')
                ->limit($limit)
                ->get();

            // Transform the data for frontend consumption
            $callsData = $calls->map(function($call) {
                return [
                    'id' => $call->id,
                    'uniqueid' => $call->uniqueid,
                    'user_id' => $call->user_id,
                    'user_name' => $call->user ? $call->user->name : null,
                    'extension' => $call->extension,
                    'client_id' => $call->client_id,
                    'client_type' => $call->client_type,
                    'number' => $call->number,
                    'call_type' => $call->call_type,
                    'state' => $call->state,
                    'dialed_time' => $call->dialed_time?->toISOString(),
                    'answered_time' => $call->answered_time?->toISOString(),
                    'duration' => $call->duration,
                    'message' => $call->message,
                    'task_id' => $call->task_id,
                    'status_color' => $call->status_color,
                    'status_icon' => $call->status_icon,
                    'created_at' => $call->created_at->toISOString(),
                    'updated_at' => $call->updated_at->toISOString()
                ];
            });

            return response()->json([
                'success' => true,
                'data' => $callsData,
                'count' => $callsData->count(),
                'client_id' => $clientId,
                'client_type' => $clientType
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch call history: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Store a new call record
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'uniqueid' => 'nullable|string|max:255',
            'extension' => 'nullable|string|max:10',
            'client_id' => 'required|integer',
            'client_type' => 'string|in:client,customer,task',
            'number' => 'required|string|max:20',
            'call_type' => 'string|in:inbound,outbound',
            'state' => 'string|max:50',
            'dialed_time' => 'nullable|date',
            'answered_time' => 'nullable|date',
            'message' => 'nullable|string',
            'task_id' => 'nullable|integer'
        ]);

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

        try {
            $callData = $request->all();
            $callData['user_id'] = Auth::id();
            $callData['client_type'] = $callData['client_type'] ?? 'client';
            $callData['call_type'] = $callData['call_type'] ?? 'outbound';
            $callData['state'] = $callData['state'] ?? 'dialing';
            
            // Resolve extension if not provided
            if (empty($callData['extension'])) {
                $callData['extension'] = \App\Modules\ThreeCX\Services\ThreeCXExtensionResolver::getExtensionForUser();
            }

            $call = Call::create($callData);

            return response()->json([
                'success' => true,
                'message' => 'Call record created successfully',
                'data' => [
                    'id' => $call->id,
                    'uniqueid' => $call->uniqueid,
                    'user_id' => $call->user_id,
                    'extension' => $call->extension,
                    'client_id' => $call->client_id,
                    'client_type' => $call->client_type,
                    'number' => $call->number,
                    'call_type' => $call->call_type,
                    'state' => $call->state,
                    'dialed_time' => $call->dialed_time?->toISOString(),
                    'answered_time' => $call->answered_time?->toISOString(),
                    'message' => $call->message,
                    'task_id' => $call->task_id,
                    'created_at' => $call->created_at->toISOString()
                ]
            ], 201);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create call record: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Update a call record
     *
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'state' => 'string|max:50',
            'answered_time' => 'nullable|date',
            'message' => 'nullable|string'
        ]);

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

        try {
            $call = Call::findOrFail($id);
            
            // Only allow updating calls from the current user or admin
            $user = Auth::user();
            $isAdmin = $user && (
                str_contains(strtolower($user->email ?? ''), 'administrator') ||
                str_contains(strtolower($user->role ?? ''), 'admin') ||
                $user->id === 1
            );
            
            if ($call->user_id !== Auth::id() && !$isAdmin) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized to update this call record'
                ], 403);
            }

            $call->update($request->only(['state', 'answered_time', 'message']));

            return response()->json([
                'success' => true,
                'message' => 'Call record updated successfully',
                'data' => [
                    'id' => $call->id,
                    'state' => $call->state,
                    'answered_time' => $call->answered_time?->toISOString(),
                    'message' => $call->message,
                    'updated_at' => $call->updated_at->toISOString()
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to update call record: ' . $e->getMessage()
            ], 500);
        }
    }
}
