<?php

namespace App\Http\Controllers\SMS;

use App\Http\Controllers\Controller;
use App\Models\CampaignList;
use App\Services\MessageProcessService;
use Carbon\Carbon;
use App\Models\Number;
use App\Helpers\Helper;
use App\Models\Message;
use App\Jobs\SentSMSJob;
use App\Models\CampaignSms;
use App\Models\JobsHistory;
use App\Models\ScheduleSMS;
use App\Models\SMSActivity;
use App\Jobs\ScheduleSmsJob;
use Illuminate\Http\Request;
use App\Jobs\ScheduleProcess;
use App\Models\SenderIdRequest;
use Illuminate\Support\Facades\DB;

class CampaignController extends Controller
{
    use Helper;

    public function __construct()
    {
        $this->model = new CampaignSms();
    }

    public function index()
    {
        if (!can('campaign_sms_view')) {
            return $this->notPermitted();
        }

        $perPage = request()->input('perPage');
        $user = auth()->user();
        $keyword = input('phone');
        $camping_id = input('camping_id');
        $start_date = input('start_date');
        $end_date = input('end_date');
        $status = input('status');

        $data = SmsActivity::with(['numbers', 'message', 'sender'])->where('user_id', $user->id)
            ->whereHas('numbers', function ($query) use ($keyword, $camping_id) {
                $query->where('type', '=', 2);
                if ($keyword){
                    $query->where('phone', 'LIKE', "%$keyword%");
                }
                if ($camping_id){
                    $query->where('type', 2);
                    $query->where('type_id', $camping_id);
                }
            })
            ->when($keyword, function ($query) use ($keyword) {
                $query->whereHas('numbers', function ($query) use ($keyword) {
                    $query->where('phone', 'LIKE', "%$keyword%");
                });
            })
            ->when(($start_date || $end_date), function ($query) use ($start_date, $end_date) {
                if ($start_date) {
                    $query->where('created_at', '>=', $start_date);
                }
                if ($end_date) {
                    $query->where('created_at', '<=', $end_date);
                }
            })
            ->when(($status), function ($query) use ($status) {
                if ($status == 'pending') {
                    $query->where('job_status', 0);
                }
                if ($status == 'delivered') {
                    $query->where('job_status', 1);
                    $query->where('api_status', 9000);
                }
                if ($status == 'failed') {
                    $query->where('job_status', 1);
                    $query->where('api_status', '!=', 9000);
                }
            })
            ->orderBy('id', 'desc')->paginate($perPage);

        return returnData(2000, $data);
    }


    public function create()
    {
        //
    }

    public function store(Request $request)
    {
        if (!can('campaign_sms_add')) {
            return $this->notPermitted();
        }

        try {
            $validate = $this->model->validate($request->all());

            if ($validate->fails()) {
                return returnData(3000, $validate->errors(), 'Validation Failed');
            }

            $sender_id_type = $request->input('sender_id_type');
            $numberGroup = $request->input('campaign_id');
            $isScheduleSMS = $request->input('schedule') > 0 ? true : false;
            $content_type = $request->input('content_type');
            $sms_type = $sender_id_type == 1 ? 'T' : 'P';
            $messageBody = $request->input('body');
//            $characterCount = strlen($messageBody);
            $characterCount = ($content_type == 3) ? mb_strlen($messageBody, "UTF-8") : strlen($messageBody);

            $campaing = CampaignList::where('id', $numberGroup)->first();
            $phoneNumbersInputArray = Number::where('type_id', $numberGroup)->where('is_deleted', 0)->where('type', 2)->get();

            $smsParts = smsPart($characterCount, $content_type);
            if (!$smsParts->status){
                return returnData(5000, null, $smsParts->message);
            }
            $rate = $sender_id_type == 1 ? auth()->user()->masking_rate : auth()->user()->non_masking_rate;
            $balanceCheck = balanceCheck($smsParts->part, $rate, count($phoneNumbersInputArray));
            if ($balanceCheck->crrAmount < 0){
                return returnData(5000, null, "Insufficient Balance ( $balanceCheck->crrAmount )");
            }

            DB::beginTransaction();
            $service = new MessageProcessService();
            $insertMessage = $service->messageInsert([
                'messageData' => $request->all(),
                'user_id' => auth()->user()->id,
                'part' => $smsParts->part,
                'characterCount' => $characterCount,
                'ip' => request()->ip(),
                'content_type' => $content_type,
                'numbers' => $phoneNumbersInputArray,
                'sender_id_type' => $sender_id_type,
                'isScheduleSMS' => $isScheduleSMS,
                'typeId' => $campaing->id,
                'campaign_title' => $campaing->campaign_name ?? 'Campaign SMS',
                'sms_type' => $sms_type,
                'rate' => $rate,
            ], false);

            if (!$insertMessage->status) {
                DB::rollBack();
                return returnData(5000, null, $insertMessage->message);
            }

            DB::commit();
            return returnData(2000, null, 'Successfully Inserted');
        } catch (\Exception $exception) {
            DB::rollBack();
            return returnData(5000, $exception->getMessage(), $exception->getMessage());
        }
    }


    public function show($id)
    {
        //
    }

    public function edit($id)
    {
        //
    }

    public function update(Request $request, $id)
    {
        //
    }

    public function destroy($id)
    {

    }
}
