<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Util\UtilMethods;
use App\Models\kycdetail;
use App\Models\KycThirdPartyFirstApprovalSequence;
use App\Models\SmallFormatAds;
use App\Models\SmallFormatDetails;
use App\Models\User;
use App\Models\UserAdmin;
use App\Models\SmallFormatReceipts;
use Barryvdh\DomPDF\Facade\Pdf;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class SmallFormatController extends Controller
{

    private $successStatusCode = 200;
    private $createStatusCode = 201;
    private $errorStatusCode = 422;

    public function __construct() {
        // $this->middleware('auth:api');
        $this->middleware('check.multi.guard'); // Then apply your custom middleware
    }

    public function createSmallFormatAds(Request $request) {


        if(empty($request->type)){
            $userId = Auth::guard('api')->user()->id;
        }elseif($request->type == "admin"){
            $userId = $request->ud;
        }
        $userObj = User::findOrFail($userId);
        if(is_null($userId)) {
            Log::error('User not found with id: ' . $userId);
            return response()->json(['success' => false, 'data' => 'User not found with id'], $this->errorStatusCode);
        }

        $validate = Validator::make($request->all(), [
            'purpose' => 'required|string',
            'signAddress' => 'required|string',
            'lga' =>  'required|string',
            'propertyOwnerPhone' =>  'required|digits:11',
            'propertyOwnerEmail' => 'required|email',
            'longitude' => 'required|numeric|between:-180,180',
            'latitude' => 'required|numeric|between:-90,90',
            'smallFormatDetails' => 'present|array',
            'smallFormatDetails.smallFormatInfo.*.typeSign' => 'required|string',
            'smallFormatDetails.smallFormatInfo.*.dimensionSign' => 'required|integer',
            'smallFormatDetails.smallFormatInfo.*.setbackDistance' => 'required|integer',
            'smallFormatDetails.smallFormatInfo.*.length' => 'required|integer',
            'smallFormatDetails.smallFormatInfo.*.breadth' => 'required|integer',
            'smallFormatDetails.smallFormatInfo.*.signFormat' => 'required|string|in:Portrait,Landscape',
            'smallFormatDetails.smallFormatInfo.*.signSite' => 'required|string|in:Onpremise,Offpremise',
            'smallFormatDetails.smallFormatInfo.*.illumination' => 'required|string|in:None,Internal,External,Backlit,Frontlit',
            'smallFormatDetails.smallFormatInfo.*.interactivity' => 'required|string|in:None/Static,Changing,Flashing,Others',
            'smallFormatDetails.smallFormatInfo.*.electricitySource' => 'required|string|in:Phcn,Solar,Generator,Inverter,Other',
            'smallFormatDetails.smallFormatInfo.*.photoMontage' => 'nullable|string'
        ]);

        if($validate->fails()) {
             return response()->json(['errors' => $validate->errors()->all()], $this->errorStatusCode);
        }

        $smallAdsInput = $request->all();
        $count = count($smallAdsInput['smallFormatDetails']['smallFormatInfo']) - 1;

        $rmRole = [2,3];
        $getAssignedOfficer  = UserAdmin::where('department', 'Registry')->whereIn('admin_role_id', $rmRole)->pluck('id')->toArray();
        $officerCounter = [];
        foreach ($getAssignedOfficer as $officer) {
            $counter = SmallFormatAds::where('assigned_officer', (string) $officer)->count();
            $officerCounter[$officer] = $counter;
        }

        $leastOfficer = array_search(min($officerCounter), $officerCounter);
        $getLeastOfficer = UserAdmin::where('id', (string) $leastOfficer)->first();

        $smallFormatAds = new SmallFormatAds();
        $smallFormatAds->purpose_application = strtolower($smallAdsInput['purpose']);
        $smallFormatAds->address_site = strtolower($smallAdsInput['signAddress']);
        $smallFormatAds->lga = strtolower($smallAdsInput['lga']);
        $smallFormatAds->property_owner_phone = $smallAdsInput['propertyOwnerPhone'];
        $smallFormatAds->property_owner_email = strtolower($smallAdsInput['propertyOwnerEmail']);
        $smallFormatAds->longitude = $smallAdsInput['longitude'];
        $smallFormatAds->latitude = $smallAdsInput['latitude'];
        $smallFormatAds->payment_id = $this->smallFormatAds();
        $smallFormatAds->assigned_officer = (string) $getLeastOfficer->id;
        $saveDetails = $userObj->smallFormatAds()->save($smallFormatAds);
        $output [] = $saveDetails;

        $utilObj  =  new UtilMethods();
        for($i=0; $i <= $count; $i++) {
            $smallFormatDetails = new SmallFormatDetails();
            $smallFormatDetails->type_signs = $utilObj->capitalizeFirstWordInString($smallAdsInput['smallFormatDetails']['smallFormatInfo'][$i]['typeSign']);
            $smallFormatDetails->dimension_sign = $smallAdsInput['smallFormatDetails']['smallFormatInfo'][$i]['dimensionSign'];
            $smallFormatDetails->setback_distance = $smallAdsInput['smallFormatDetails']['smallFormatInfo'][$i]['setbackDistance'];
            $smallFormatDetails->length = $smallAdsInput['smallFormatDetails']['smallFormatInfo'][$i]['length'];
            $smallFormatDetails->breadth = $smallAdsInput['smallFormatDetails']['smallFormatInfo'][$i]['breadth'];
            $smallFormatDetails->sign_format = strtolower($smallAdsInput['smallFormatDetails']['smallFormatInfo'][$i]['signFormat']);
            $smallFormatDetails->sign_site = strtolower($smallAdsInput['smallFormatDetails']['smallFormatInfo'][$i]['signSite']);
            $smallFormatDetails->illumination = strtolower($smallAdsInput['smallFormatDetails']['smallFormatInfo'][$i]['illumination']);
            $smallFormatDetails->interactivity = strtolower($smallAdsInput['smallFormatDetails']['smallFormatInfo'][$i]['interactivity']);
            $smallFormatDetails->electricity_source = strtolower($smallAdsInput['smallFormatDetails']['smallFormatInfo'][$i]['electricitySource']);
            if(!is_null($smallAdsInput['smallFormatDetails']['smallFormatInfo'][$i]['photoMontage'])) {
                $smallFormatDetails->photo_montage = $utilObj->convertBase64toImage($smallAdsInput['smallFormatDetails']['smallFormatInfo'][$i]['photoMontage']);
            }

            $smallAdsObj = SmallFormatAds::find($output[0]['id']);
            $smallAdsObj->smallFormatDetails()->save($smallFormatDetails);
        }

        $getResponse = SmallFormatAds::where('id', $smallAdsObj->id)->with(['smallFormatDetails'])->get();
        return response()->json(['success' => true, 'data' => $getResponse], $this->successStatusCode);
    }

    public function getAllSmallFormatAds(Request $request) {

        $userId = Auth::guard('api')->user()->id;
        
        $keyword = $request->input('search');
        $smallFormatAds = SmallFormatAds::where('user_id', $userId)->with(['smallFormatDetails']);

        if($keyword) {
            $smallFormatAds->where(function ($query) use ($keyword) {
                $query->where('purpose_application', 'like', '%' . $keyword . '%')
                    ->orWhere('address_site', 'like', '%' . $keyword . '%')
                    ->orWhere('lga', 'like', '%' . $keyword . '%')
                    ->orWhere('property_owner_phone', 'like', '%' . $keyword . '%')
                    ->orWhere('property_owner_email', 'like', '%' . $keyword . '%');
            });

            $smallFormatAds->orWhereHas('smallFormatDetails', function ($query) use ($keyword) {
                $query->where('type_signs', 'like', '%' . $keyword . '%')
                    ->orWhere('sign_format', 'like', '%' . $keyword . '%')
                    ->orWhere('sign_site','like', '%' . $keyword . '%')
                    ->orWhere('illumination', 'like', '%' . $keyword . '%')
                    ->orWhereHas('appHistorySmallFormatDetails', function ($query) use ($keyword) {
                        $query->where('purpose_application', 'like', '%' . $keyword . '%');
                    });

            });
        }

        $getAllItems = $smallFormatAds->orderBy('created_at', 'desc')->paginate(20);
        if($getAllItems->count() > 0) {
            return response()->json(['success' => true, 'data' => $getAllItems], $this->successStatusCode);
        } else {
            return response()->json(['success' => false, 'data' => 'No items found'], $this->errorStatusCode);
        }
    }

    public function getOneSmallFormatApplication($smallFormatId) {
        try {

            $smallFormatObj = SmallFormatAds::findOrFail($smallFormatId);

            if (Auth::guard('api')->user()->id == (string) $smallFormatObj->user_id) {
                // Retrieve the small format ad with its details
                $getSingleSmallFormatAds = SmallFormatAds::where('id', $smallFormatObj->id)->with(['smallFormatDetails'])->first();

                if (is_null($getSingleSmallFormatAds)) {
                    return response()->json(['success' => false, 'data' => 'Small Format ads does not exist'], $this->errorStatusCode);
                }
                return response()->json(['success' => true, 'data' => $getSingleSmallFormatAds], $this->successStatusCode);
            } else {
                return response()->json(['success' => false, 'data' => 'Cannot access the Small Format ads'], $this->errorStatusCode);
            }
        } catch (ModelNotFoundException $e) {

            return response()->json(['success' => false, 'data' => 'Small Format ads does not exist'], $this->errorStatusCode);
        } catch (Exception $e) {

            return response()->json(['success' => false, 'data' => 'An error occurred'], $this->errorStatusCode);
        }
    }

    public function getOneSmallFormatDetailsApplication($smallFormatDetailsId) {

        try {
            $getSmallDetails = SmallFormatDetails::findOrFail($smallFormatDetailsId);
            return response()->json(['success' => true, 'data' => $getSmallDetails], $this->successStatusCode);

        } catch (ModelNotFoundException $e) {
            return response()->json(['success' => false, 'data' => 'Small Format details does not exist'], $this->errorStatusCode);
        }
    }

    public function getSmallFormatApprovalLetter($smallFormatDetailsId) {

        $smallFormatDetailObj = SmallFormatDetails::findOrFail($smallFormatDetailsId);

        if($smallFormatDetailObj->adprice_payment_status !== 'paid') {
            return response()->json(['success' => false, 'data' => 'small format details is not yet fully paid'], $this->errorStatusCode);
        }

        if ($smallFormatDetailObj->reference_id == null) {
            $refno = $this->getRefNo();
            $smallFormatDetailObj->update(['reference_id' => $refno]);
        }

        $getSmallFormat = SmallFormatAds::where('id', $smallFormatDetailObj->small_format_ads_id)->get();
        $getUserInfo = User::where('id', $getSmallFormat[0]['user_id'])->get();
        $companyName = $getUserInfo[0]['business_name'];
        $getKycDetails = kycdetail::where('user_id', $getUserInfo[0]['id'])->get();
        $getAddress = $getKycDetails[0]['full_address'];
        $getLga = $getKycDetails[0]['lga'];
        $getBustop = $getKycDetails[0]['bustop'];
        $location = $getSmallFormat[0]['address_site'];
        $date = Carbon::parse($smallFormatDetailObj->created_at);
        $endYear = Carbon::create($date->year, 12, 31);
        $diffInMonths = $date->diffInMonths($endYear);
        $diffInMonthsInWords = UtilMethods::smallFormatInMonth($diffInMonths);

        $data = [
           'date' => Carbon::parse($smallFormatDetailObj->created_at)->format('jS F, Y'),
            'refno' => $smallFormatDetailObj->reference_id,
            'company' => $companyName,
            'address' => $getAddress,
            'bustop' => $getBustop,
            'lga' => $getLga,
            'startDate' => $date->format('F, Y'),
            'endDate' => $endYear->format('d F, Y'),
            'siteLocation' => $location,
            'appNumber' => $smallFormatDetailsId,
            'signType' => $smallFormatDetailObj->type_signs,
            'numberMonths' => $diffInMonths
        ];

        $pdf = Pdf::loadView('smallformat', compact('data'));
        $fileObj = $pdf->download('smallformat.pdf');

        $userObj = User::find($getSmallFormat[0]['user_id']);
        $body = "We are pleased to inform you that your application for small format ads has been approved. Please find your approval letter attached";
        $templateData = [
            'body' => $body,
            'name' => $userObj->company_name
        ];
        $templateContent = view('hodeoitemplate', $templateData)->render();
        UtilMethods::smallFormatSendApproval($userObj->email, $templateContent, $fileObj);
        Log::info('email sent to ' . $userObj->email);

    }

    private function smallFormatAds() {
        $prefix = 'smallformat';
        $batchkey = Carbon::now()->format('YmdHis');
        $suffix = rand(100, 999);
        return $prefix.$batchkey.$suffix;
    }

    private function getRefNo() {
        $prefix = 'LASAA/SF';
        $batchKey = Carbon::now()->format('Y/M');
        $sequence = KycThirdPartyFirstApprovalSequence::firstOrCreate([]);
        $lastNumber = $sequence->last_number + 1;
        $sequence->update(['last_number' => $lastNumber]);
        return $prefix . '/' . $batchKey . '/' . $lastNumber;
    }
    
    public function getSmallformatDownloadables($id) {
        $user = Auth::user();
        $check = SmallFormatReceipts::where('small_format_ads_id', $id)->exists();
        if($check){
            $getreceipts = SmallFormatReceipts::where('small_format_ads_id', $id)->get()->toArray();
        
            return response()->json(['data' => $getreceipts], 200);
        }else{
            return response()->json(['data' => 'No Downloadables Yet!'], 422);
        }
        
    }



}
