<?php

namespace App\Modules\Twilio\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Twilio\Services\TwilioServiceInterface;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Exception;

/**
 * Twilio API Controller
 * 
 * Handles SMS operations and Twilio API integration
 */
class TwilioApiController extends Controller
{
    protected $twilioService;
    
    public function __construct(TwilioServiceInterface $twilioService)
    {
        $this->twilioService = $twilioService;
    }
    
    /**
     * Send SMS message
     */
    public function sendSMS(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'send_to' => 'required|string',
                'message' => 'required|string|max:1600'
            ]);
            
            $result = $this->twilioService->sendSMS(
                $request->get('send_to'),
                $request->get('message')
            );
            
            if ($result['success']) {
                return response()->json([
                    'success' => true,
                    'message_sid' => $result['message_sid'],
                    'status' => $result['status']
                ], 200);
            } else {
                return response()->json([
                    'success' => false,
                    'error' => $result['error']
                ], 400);
            }
            
        } catch (Exception $e) {
            Log::error('Twilio API Error - sendSMS: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'error' => 'Failed to send SMS',
                'message' => $e->getMessage()
            ], 500);
        }
    }
    
    /**
     * Send task-specific SMS
     */
    public function sendTaskSMS(Request $request, $taskId): JsonResponse
    {
        try {
            $request->validate([
                'send_to' => 'required|string',
                'message' => 'required|string|max:1600'
            ]);
            
            $result = $this->twilioService->sendTaskSMS(
                $taskId,
                $request->get('send_to'),
                $request->get('message')
            );
            
            if ($result['success']) {
                return response()->json([
                    'success' => true,
                    'message_sid' => $result['message_sid'],
                    'status' => $result['status'],
                    'notification_id' => $result['notification_id']
                ], 200);
            } else {
                return response()->json([
                    'success' => false,
                    'error' => $result['error']
                ], 400);
            }
            
        } catch (Exception $e) {
            Log::error('Twilio API Error - sendTaskSMS: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'error' => 'Failed to send task SMS',
                'message' => $e->getMessage()
            ], 500);
        }
    }
    
    /**
     * Send completion notification SMS
     */
    public function sendCompletionSMS(Request $request, $taskId): JsonResponse
    {
        try {
            $request->validate([
                'send_to' => 'required|string',
                'message' => 'required|string|max:1600'
            ]);
            
            $result = $this->twilioService->sendCompletionSMS(
                $taskId,
                $request->get('send_to'),
                $request->get('message')
            );
            
            if ($result['success']) {
                return response()->json([
                    'success' => true,
                    'message_sid' => $result['message_sid'],
                    'status' => $result['status'],
                    'notification_id' => $result['notification_id']
                ], 200);
            } else {
                return response()->json([
                    'success' => false,
                    'error' => $result['error']
                ], 400);
            }
            
        } catch (Exception $e) {
            Log::error('Twilio API Error - sendCompletionSMS: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'error' => 'Failed to send completion SMS',
                'message' => $e->getMessage()
            ], 500);
        }
    }
    
    /**
     * Validate phone number format
     */
    public function validatePhoneNumber(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'phone_number' => 'required|string'
            ]);
            
            $result = $this->twilioService->validatePhoneNumber($request->get('phone_number'));
            
            return response()->json([
                'success' => true,
                'valid' => $result['valid'],
                'formatted' => $result['formatted'],
                'country_code' => $result['country_code'] ?? null
            ]);
            
        } catch (Exception $e) {
            Log::error('Twilio API Error - validatePhoneNumber: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'error' => 'Failed to validate phone number',
                'message' => $e->getMessage()
            ], 500);
        }
    }
    
    /**
     * Format phone number
     */
    public function formatPhoneNumber(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'phone_number' => 'required|string'
            ]);
            
            $result = $this->twilioService->formatPhoneNumber($request->get('phone_number'));
            
            return response()->json([
                'success' => true,
                'formatted' => $result['formatted'],
                'country_code' => $result['country_code'] ?? null
            ]);
            
        } catch (Exception $e) {
            Log::error('Twilio API Error - formatPhoneNumber: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'error' => 'Failed to format phone number',
                'message' => $e->getMessage()
            ], 500);
        }
    }
    
    /**
     * Get SMS delivery status
     */
    public function getDeliveryStatus(Request $request, $messageSid): JsonResponse
    {
        try {
            $result = $this->twilioService->getDeliveryStatus($messageSid);
            
            return response()->json([
                'success' => true,
                'status' => $result['status'],
                'details' => $result['details']
            ]);
            
        } catch (Exception $e) {
            Log::error('Twilio API Error - getDeliveryStatus: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'error' => 'Failed to get delivery status',
                'message' => $e->getMessage()
            ], 500);
        }
    }
    
    /**
     * Get SMS history
     */
    public function getSMSHistory(Request $request): JsonResponse
    {
        try {
            $result = $this->twilioService->getSMSHistory(
                $request->get('limit', 50),
                $request->get('offset', 0)
            );
            
            return response()->json([
                'success' => true,
                'messages' => $result['messages'],
                'total' => $result['total']
            ]);
            
        } catch (Exception $e) {
            Log::error('Twilio API Error - getSMSHistory: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'error' => 'Failed to get SMS history',
                'message' => $e->getMessage()
            ], 500);
        }
    }
    
    
} 