<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\SMSService;
use App\ResponseHandler\Response;
use Symfony\Component\HttpFoundation\Response as HttpResponse;
use Illuminate\Http\Response as LaravelResponse;

class SMSController extends Controller
{
    protected $response;

    public function __construct(Response $response)
    {
        $this->response = $response;
    }

    /**
     * Send SMS to multiple mobile numbers using template
     * POST /api/sms/send
     */
    public function sendSMS(Request $request)
    {
        try {
            // Validate request data
            $request->validate([
                'mobileNumberArray' => 'required|array',
                'mobileNumberArray.*' => 'required|string|min:10|max:15',
                'message' => 'required|string'
            ]);

            $mobileNumbers = $request->input('mobileNumberArray');
            $message = $request->input('message');

            
            // Send SMS using SMSService
            $smsResponse = SMSService::sendSms($mobileNumbers, $message);

            // Parse the response (assuming JSON response from SMS provider)
            $decodedResponse = json_decode($smsResponse, true);

            if ($decodedResponse && isset($decodedResponse['status']) && $decodedResponse['status'] === 'success') {
                return $this->response->respondWithData(
                    'SMS sent successfully',
                    [
                        'sent_to_count' => count($mobileNumbers),
                        'mobile_numbers' => $mobileNumbers,
                        'message' => $message,
                        'sms_response' => $decodedResponse
                    ],
                    new LaravelResponse()
                );
            } else {
                return $this->response->respondWithError(
                    'Failed to send SMS: ' . ($decodedResponse['error'] ?? 'Unknown error'),
                    500
                );
            }

        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->response->respondWithError(
                'Validation failed: ' . implode(', ', array_flatten($e->errors())),
                422
            );
        } catch (\Exception $e) {
            return $this->response->respondWithError(
                'Failed to send SMS: ' . $e->getMessage(),
                500
            );
        }
    }


    /**
     * Send SMS to all head voters (Type 1)
     * POST /api/sms/sendToAll
     */
    public function sendToAll(Request $request)
    {
        try {
            // Validate request data
            $request->validate([
                'header' => 'required|string',
                'message' => 'required|string'
            ]);

            $header = $request->input('header');
            $message = $request->input('message');

            // Get all mobile numbers using GiftService method
            $giftService = app(\App\Services\GiftService::class);
            $mobileResult = $giftService->getAllMobileNumbers();

            if ($mobileResult['status'] === 'error') {
                return $this->response->respondWithError($mobileResult['message'], 400);
            }

            if (empty($mobileResult['mobile_numbers'])) {
                return $this->response->respondWithError('No mobile numbers found for head voters', 404);
            }

            // Send SMS using common method
            $smsResponse = SMSService::sendAnnouncement(
                $header,
                $message,
                $mobileResult['mobile_numbers']
            );

            $decodedResponse = json_decode($smsResponse, true);

            if ($decodedResponse && $decodedResponse['status'] === 'success') {
                return $this->response->respondWithData(
                    'SMS sent successfully to all head voters',
                    [
                        'total_sent' => $mobileResult['count'],
                        'message' => $message,
                        'header' => $header,
                        'sms_response' => $decodedResponse
                    ],
                    new LaravelResponse()
                );
            } else {
                return $this->response->respondWithError(
                    'Failed to send SMS: ' . ($decodedResponse['error'] ?? 'Unknown error'),
                    500
                );
            }

        } catch (\Exception $e) {
            return $this->response->respondWithError(
                'Failed to send SMS to all: ' . $e->getMessage(),
                500
            );
        }
    }

    /**
     * Send SMS to gifted ration card holders (Type 2)
     * POST /api/sms/sendToGifted
     */
    public function sendToGifted(Request $request)
    {
        try {
            // Validate request data
            $request->validate([
                'header' => 'required|string',
                'message' => 'required|string',
                'gift_id' => 'required|integer'
            ]);

            $header = $request->input('header');
            $message = $request->input('message');
            $giftId = $request->input('gift_id');

            // Get gifted mobile numbers using GiftService
            $giftService = app(\App\Services\GiftService::class);
            $mobileResult = $giftService->getGiftedMobileNumbers($giftId);

            if ($mobileResult['status'] === 'error') {
                return $this->response->respondWithError($mobileResult['message'], 400);
            }

            if (empty($mobileResult['mobile_numbers'])) {
                return $this->response->respondWithError(
                    'No mobile numbers found for gifted ration cards for gift ID: ' . $giftId,
                    404
                );
            }

            // Send SMS using common method
            $smsResponse = SMSService::sendAnnouncement(
                $header,
                $message,
                $mobileResult['mobile_numbers']
            );

            $decodedResponse = json_decode($smsResponse, true);

            if ($decodedResponse && $decodedResponse['status'] === 'success') {
                return $this->response->respondWithData(
                    'SMS sent successfully to gifted ration card holders',
                    [
                        'total_sent' => $mobileResult['count'],
                        'gift_id' => $giftId,
                        'gift_name' => $mobileResult['gift_name'],
                        'message' => $message,
                        'header' => $header,
                        'sms_response' => $decodedResponse
                    ],
                    new LaravelResponse()
                );
            } else {
                return $this->response->respondWithError(
                    'Failed to send SMS: ' . ($decodedResponse['error'] ?? 'Unknown error'),
                    500
                );
            }

        } catch (\Exception $e) {
            return $this->response->respondWithError(
                'Failed to send SMS to gifted: ' . $e->getMessage(),
                500
            );
        }
    }

    /**
     * Send SMS to pending (non-gifted) ration card holders (Type 3)
     * POST /api/sms/sendToPending
     */
    public function sendToPending(Request $request)
    {
        try {
            // Validate request data
            $request->validate([
                'header' => 'required|string',
                'message' => 'required|string',
                'gift_id' => 'required|integer'
            ]);

            $header = $request->input('header');
            $message = $request->input('message');
            $giftId = $request->input('gift_id');

            // Get pending mobile numbers using GiftService
            $giftService = app(\App\Services\GiftService::class);
            $mobileResult = $giftService->getPendingMobileNumbers($giftId);

            if ($mobileResult['status'] === 'error') {
                return $this->response->respondWithError($mobileResult['message'], 400);
            }

            if (empty($mobileResult['mobile_numbers'])) {
                return $this->response->respondWithError(
                    'No mobile numbers found for pending ration cards for gift ID: ' . $giftId,
                    404
                );
            }

            // Send SMS using common method
            $smsResponse = SMSService::sendAnnouncement(
                $header,
                $message,
                $mobileResult['mobile_numbers']
            );

            $decodedResponse = json_decode($smsResponse, true);

            if ($decodedResponse && $decodedResponse['status'] === 'success') {
                return $this->response->respondWithData(
                    'SMS sent successfully to pending ration card holders',
                    [
                        'total_sent' => $mobileResult['count'],
                        'gift_id' => $giftId,
                        'gift_name' => $mobileResult['gift_name'],
                        'message' => $message,
                        'header' => $header,
                        'sms_response' => $decodedResponse
                    ],
                    new LaravelResponse()
                );
            } else {
                return $this->response->respondWithError(
                    'Failed to send SMS: ' . ($decodedResponse['error'] ?? 'Unknown error'),
                    500
                );
            }

        } catch (\Exception $e) {
            return $this->response->respondWithError(
                'Failed to send SMS to pending: ' . $e->getMessage(),
                500
            );
        }
    }

    /**
     * Send SMS to custom mobile numbers (Type 4) - Updated existing method
     * POST /api/sms/send
     */
    public function sendCustomSMS(Request $request)
    {
        try {
            // Validate request data (support both formats)
            $request->validate([
                'header' => 'required|string',
                'message' => 'required|string',
                'mobileNumbers' => 'required|array',
                'mobileNumbers.*' => 'required|string'
            ]);

            $header = $request->input('header');
            $message = $request->input('message');
            $mobileNumbers = $request->input('mobileNumbers');

            // Send SMS using common method
            $smsResponse = SMSService::sendAnnouncement(
                $header,
                $message,
                $mobileNumbers
            );

            $decodedResponse = json_decode($smsResponse, true);

            if ($decodedResponse && $decodedResponse['status'] === 'success') {
                return $this->response->respondWithData(
                    'SMS sent successfully to custom mobile numbers',
                    [
                        'total_sent' => count($mobileNumbers),
                        'message' => $message,
                        'header' => $header,
                        'sms_response' => $decodedResponse
                    ],
                    new LaravelResponse()
                );
            } else {
                return $this->response->respondWithError(
                    'Failed to send SMS: ' . ($decodedResponse['error'] ?? 'Unknown error'),
                    500
                );
            }

        } catch (\Exception $e) {
            return $this->response->respondWithError(
                'Failed to send custom SMS: ' . $e->getMessage(),
                500
            );
        }
    }
}
