<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\mobilead;
use App\Models\onpremise;
use App\Models\StreetLampsAds;
use App\Models\ThirdPartyMobile;
use App\Models\UserAdmin;
use App\Models\StreetLampsAdsApplicationPricing;
use App\Models\Apphistory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class UserAdsDetailsController extends Controller
{
    //
//    public function __construct() {
//        $this->middleware('auth:api');
//    }

    public function getUserMobileAds($mobileId) {

        //$user = Auth::user();

        $getAllMobileAdsDetails = mobilead::where('id', $mobileId)->with(['user','appHistoryMobile', 'permitStepMobile',
                                                                                        'vehicleMobile','mobileAdsVehicleLicense' ])->get();
//        $getLineManager = UserAdmin::where('id', (string) $getAllMobileAdsDetails[0]['assigned_officer'])->get();
        $zones = [$getAllMobileAdsDetails[0]['zone'], ];
        $getLineManager = UserAdmin::where('department', 'Mobile_advert')->where('zone',  $getAllMobileAdsDetails[0]['zone'])
                                ->orWhere('zone2', $getAllMobileAdsDetails[0]['zone'])->get();
       $getHod = $getLineManager[0]['line_manager'];
        $convertId = (integer) $getHod;
        if(count($getAllMobileAdsDetails) == 0) {
            return response()->json(['data' => 'There is no mobile ads with that id details'], 422);
        } else {
            return response()->json(['data' => $getAllMobileAdsDetails, 'assigned_hod' => $convertId ],200);
//            return response()->json(['data' => $getAllMobileAdsDetails],200);
        }
    }

    public function getThirdPartyMobileAds($thirdPartyId) {

        //$user = Auth::user();
        $getThirdPartyMobileDetails = ThirdPartyMobile::where('id', $thirdPartyId)->with(['user',
                                                                                                    'vehicleThirdPartyMobile', 'thirdPartyMobileVehicleLincense'])->get();
        $getLineManager = UserAdmin::where('id', (string) $getThirdPartyMobileDetails[0]['assigned_officer'])->get();
        $getHod = $getLineManager[0]['line_manager'];
        $convertId = (integer) $getHod;

        if(count($getThirdPartyMobileDetails) == 0) {
            return response()->json(['data' => 'There is no third party mobile ads with that id details'], 422);
        } else {
            return response()->json(['data' => $getThirdPartyMobileDetails, 'assigned_hod' => $convertId], 200);
        }
    }
    
    public function getStreetLampApplicationPricing(){
        
        $getPrices = StreetLampsAdsApplicationPricing::all();
        return response()->json(['success' => true, 'data' => $getPrices], 200);
    }
    
    public function updateStreetLampApplicationPricing(Request $request, $id) {
        
        $validator = Validator::make($request->all(), [
            'type_of_sign' => ['required', 'string', 'max:255'],
            'app_price' => ['required', 'numeric', 'min:0'],
        ]);
    
        // Find the record by ID
        $pricing = StreetLampsAdsApplicationPricing::findOrFail($id);
        
        if($validator->fails()) {
            return response()->json(['errors' => $validated->errors()->all()], $this->errorStatusCode);
        }
        
        $validated = $validator->validated();
    
        $pricing->update($validated);
    
        return response()->json(['success' => true, 'data' => 'Pricing record updated successfully'], 200);
    }

    public function getStreetLampAds($streetLampId) {

        //$user = Auth::user();

        $getStreetLampsDetails = StreetLampsAds::where('id', $streetLampId)->with(['user', 'appHistoryStreetLamp', 'permitStepStreetLamp',
                                                                 'streetLampInfo'])->get();

        $getLineManager = UserAdmin::where('id', (string) $getStreetLampsDetails[0]['assigned_officer'])->get();
       $getHod = $getLineManager[0]['line_manager'];
        $convertId = (integer) $getHod;
        if(count($getStreetLampsDetails) == 0) {
            return response()->json(['data' => 'There is no street lamp ads with that id details'], 422);
        } else {
            return response()->json(['data' => $getStreetLampsDetails, 'assigned_hod' => $convertId], 200);
        }

    }

    public function getOnpremiseAds($onpremiseId) {

        //$user = Auth::user();

        $getOnpremiseAds = onpremise::where('id', $onpremiseId)->with(['user', 'appHistory', 'permitStepOnpremise',
                                                                                            'onpremiseInfo', 'OnPremiseRemoval' => function($query) {
                $query->latest('id')->take(1);  // Fetches only the latest record based on the created_at or another timestamp column
            },
                                                                                            'OnPremiseAdditional' => function($query) {
                $query->latest('id')->take(1);  // Fetches only the latest record based on the created_at or another timestamp column
            },
                                                                                            'OnPremiseChange' => function($query) {
                $query->latest('id')->take(1);  // Fetches only the latest record based on the created_at or another timestamp column
            },
        ])->get();
        $checkexists = Apphistory::where('onpremise_id', $onpremiseId)->exists();
        if($checkexists){
        $adsprice = Apphistory::where('onpremise_id', $onpremiseId)->get()->last();
        $price = round((double)$adsprice['ads_price'],2);
        $previous = round((double)$adsprice['previous_ads_price'],2);
        $pricetoremoveonchange = round((double)$adsprice['to_remove_ads_price'],2);
        }else{
            $price = null;
            $previous = null;
            $pricetoremoveonchange = null;
        }
        
        
        if($getOnpremiseAds[0]['status'] == "pending"){
            $calladmin = UserAdmin::select('first_name', 'last_name')->where('department', 'M_I')->where('lga',$getOnpremiseAds[0]['lga'])->where('admin_role_id', 1)->get()->toArray();
            if(empty($calladmin)){
                $calladmin = "missing branch manager admin";
            }
        }elseif($getOnpremiseAds[0]['rm_status'] == "pending"){
            $calladmin = UserAdmin::select('first_name', 'last_name')->where('department', 'M_I')->where('admin_role_id', 2)->orWhere('admin_role_id', 3)->where('zone', $getOnpremiseAds[0]['zone'])->orWhere('zone2', $getOnpremiseAds[0]['zone'])->get()->toArray();
            if(empty($calladmin)){
                $calladmin = "missing relational manager admin";
            }
        }elseif($getOnpremiseAds[0]['hod_status'] == "pending"){
            $calladmin = UserAdmin::select('first_name', 'last_name')->where('department', 'M_I')->where('admin_role_id', 5)->where('zone', $getOnpremiseAds[0]['zone'])->orWhere('zone2', $getOnpremiseAds[0]['zone'])->get()->toArray();
            if(empty($calladmin)){
                $calladmin = "missing hod admin";
            }
        }elseif($getOnpremiseAds[0]['billing_status'] == "pending"){
            $calladmin = UserAdmin::select('first_name', 'last_name')->where('department', 'Billings')->get()->toArray();
            if(empty($calladmin)){
                $calladmin = "missing billings manager admin";
            }
        }elseif($getOnpremiseAds[0]['account_status'] == "pending"){
            $calladmin = UserAdmin::select('first_name', 'last_name')->where('admin_role_id', 8)->get()->toArray();
            if(empty($calladmin)){
                $calladmin = "missing finance manager admin";
            }
        }elseif($getOnpremiseAds[0]['audit_status'] == "pending"){
            $calladmin = UserAdmin::select('first_name', 'last_name')->where('admin_role_id', 4)->get()->toArray();
            if(empty($calladmin)){
                $calladmin = "missing audit manager admin";
            }
        }elseif($getOnpremiseAds[0]['legal_status'] == "pending"){
            $calladmin = UserAdmin::select('first_name', 'last_name')->where('admin_role_id', 9)->get()->toArray();
            if(empty($calladmin)){
                $calladmin = "missing legal manager admin";
            }
        }elseif($getOnpremiseAds[0]['final_status'] == "pending"){
            $calladmin = "M.D";
        }else{
            $calladmin = "";
        }
        
        // var_dump($calladmin);die();
        
        if(count($getOnpremiseAds) == 0) {
            return response()->json(['data' => 'There is no onpremise ads with that id details' ], 422);
        } else {
            return response()->json(['data' => $getOnpremiseAds, 'ads_price' => $price, 'previous_years' => $previous, 'to_remove_ads_price' => $pricetoremoveonchange, 'admins' => $calladmin], 200);
        }
    }

    public function userDeclineStreetLampsAds($streetLampId) {

        $streetLampExist = StreetLampsAds::where('id', $streetLampId)->exists();
        if($streetLampExist) {
            StreetLampsAds::where('id', $streetLampId)->update(['status' => 'declined', 'eoi_status' => 'declined',
                                                        'hod_permit_status' => 'declined', 'final_status' => 'declined']);
            $getStreetLamp = StreetLampsAds::where('id', $streetLampId)->with(['streetLampInfo'])->get();
        } else {
            $getStreetLamp = 'Does not exist';
        }
        return response()->json(['data' => $getStreetLamp], 200);
    }
}
