<?php

namespace App\Services\Admin;

use App\Models\Attribute;
use App\Models\Lead;
use App\Models\Listing;
use App\Models\TempPublicImage;
use App\Services\BaseService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Yajra\Datatables\Datatables;
use File;

class ListingService extends BaseService
{
    private $uploadFileService;

    public function __construct()
    {
        $this->uploadFileService = resolve(UploadFileService::class);
    }

    public function listingList($request)
    {
        $listings = Listing::with('added_by', 'project', 'purpose');
        if ($request->has('project_search') && $request['project_search'] != '' && $request['project_search'] != 'null' && $request['project_search'] != 'undefined') {
            $listings->where('project_id', $request['project_search']);
        }
        if ($request->has('purpose_search') && $request['purpose_search'] != '' && $request['purpose_search'] != 'null' && $request['purpose_search'] != 'undefined') {
            $listings->where('purpose_id', $request['purpose_search']);
        }
        if ($request->has('bedSearch') && $request['bedSearch'] != '' && $request['bedSearch'] != 'null' && $request['bedSearch'] != 'undefined') {
            $listings->where('beds', $request['bedSearch']);
        }
        if ($request->has('bathSearch') && $request['bathSearch'] != '' && $request['bathSearch'] != 'null' && $request['bathSearch'] != 'undefined') {
            $listings->where('baths', $request['bathSearch']);
        }
        if ($request->has('contact_search') && $request['contact_search'] != '' && $request['contact_search'] != 'null' && $request['contact_search'] != 'undefined') {
            $listings->whereRaw("FIND_IN_SET(?, contacts)", [$request['contact_search']]);
        }
        if ($request->has('developer_search') && $request['developer_search'] != '' && $request['developer_search'] != 'null' && $request['developer_search'] != 'undefined') {
            $listings->where('developer_id', $request['developer_search']);
        }
        if ($request->has('property_type_search') && $request['property_type_search'] != '' && $request['property_type_search'] != 'null' && $request['property_type_search'] != 'undefined') {
            $listings->where('property_type_id', $request['property_type_search']);
        }
        if ($request->has('unit_type_search') && $request['unit_type_search'] != '' && $request['unit_type_search'] != 'null' && $request['unit_type_search'] != 'undefined') {
            $listings->where('unit_type_id', $request['unit_type_search']);
        }
        if ($request->has('cs_search') && $request['cs_search'] != '' && $request['cs_search'] != 'null' && $request['cs_search'] != 'undefined') {
            $listings->where('completion_status_id', $request['cs_search']);
        }
        if ($request->has('os_search') && $request['os_search'] != '' && $request['os_search'] != 'null' && $request['os_search'] != 'undefined') {
            $listings->where('ownership_status_id', $request['os_search']);
        }
        if ($request->has('ds_search') && $request['ds_search'] != '' && $request['ds_search'] != 'null' && $request['ds_search'] != 'undefined') {
            $listings->where('development_status_id', $request['ds_search']);
        }
        if ($request->has('ss_search') && $request['ss_search'] != '' && $request['ss_search'] != 'null' && $request['ss_search'] != 'undefined') {
            $listings->where('sale_status_id', $request['ss_search']);
        }
        if ($request->has('rf_search') && $request['rf_search'] != '' && $request['rf_search'] != 'null' && $request['rf_search'] != 'undefined') {
            $listings->where('rent_frequency_id', $request['rf_search']);
        }
        if (auth()->user()->type == 1) {
            $listingList = $listings->where('type', $request['type']);
        } else {
            $listingList = $listings->where(['added_by' => auth()->id(), 'type' => $request['type']]);
        }
        $datatable = Datatables::of($listingList)->rawColumns(['content']);
        return collect($datatable->make(true)->getData());
    }

    public function publicListingList($request)
    {
        $listings = Listing::with('added_by', 'project', 'purpose');
        if ($request->has('project_search') && $request['project_search'] != '' && $request['project_search'] != 'null' && $request['project_search'] != 'undefined') {
            $listings->where('project_id', $request['project_search']);
        }
        if ($request->has('purpose_search') && $request['purpose_search'] != '' && $request['purpose_search'] != 'null' && $request['purpose_search'] != 'undefined') {
            $listings->where('purpose_id', $request['purpose_search']);
        }
        if ($request->has('contact_search') && $request['contact_search'] != '' && $request['contact_search'] != 'null' && $request['contact_search'] != 'undefined') {
            $listings->whereRaw("FIND_IN_SET(?, contacts)", [$request['contact_search']]);
        }
        if ($request->has('bedSearch') && $request['bedSearch'] != '' && $request['bedSearch'] != 'null' && $request['bedSearch'] != 'undefined') {
            $listings->where('beds', $request['bedSearch']);
        }
        if ($request->has('bathSearch') && $request['bathSearch'] != '' && $request['bathSearch'] != 'null' && $request['bathSearch'] != 'undefined') {
            $listings->where('baths', $request['bathSearch']);
        }
        if ($request->has('developer_search') && $request['developer_search'] != '' && $request['developer_search'] != 'null' && $request['developer_search'] != 'undefined') {
            $listings->where('developer_id', $request['developer_search']);
        }
        if ($request->has('property_type_search') && $request['property_type_search'] != '' && $request['property_type_search'] != 'null' && $request['property_type_search'] != 'undefined') {
            $listings->where('property_type_id', $request['property_type_search']);
        }
        if ($request->has('unit_type_search') && $request['unit_type_search'] != '' && $request['unit_type_search'] != 'null' && $request['unit_type_search'] != 'undefined') {
            $listings->where('unit_type_id', $request['unit_type_search']);
        }
        if ($request->has('cs_search') && $request['cs_search'] != '' && $request['cs_search'] != 'null' && $request['cs_search'] != 'undefined') {
            $listings->where('completion_status_id', $request['cs_search']);
        }
        if ($request->has('os_search') && $request['os_search'] != '' && $request['os_search'] != 'null' && $request['os_search'] != 'undefined') {
            $listings->where('ownership_status_id', $request['os_search']);
        }
        if ($request->has('ds_search') && $request['ds_search'] != '' && $request['ds_search'] != 'null' && $request['ds_search'] != 'undefined') {
            $listings->where('development_status_id', $request['ds_search']);
        }
        if ($request->has('ss_search') && $request['ss_search'] != '' && $request['ss_search'] != 'null' && $request['ss_search'] != 'undefined') {
            $listings->where('sale_status_id', $request['ss_search']);
        }
        if ($request->has('rf_search') && $request['rf_search'] != '' && $request['rf_search'] != 'null' && $request['rf_search'] != 'undefined') {
            $listings->where('rent_frequency_id', $request['rf_search']);
        }
        $listingList = $listings->whereStatus(1);
        $datatable = Datatables::of($listingList)->rawColumns(['content']);
        return collect($datatable->make(true)->getData());
    }

    public function listingReqsList($request)
    {
        $listing = Listing::find($request['listing_id']);
        if ($listing && $listing->status == 1) {
            $area = (int)$listing->area;
            $price = (int)$listing->price;
            $leads = Lead::with('district', 'project', 'purpose', 'property_type', 'lead_status', 'lead_source', 'added_by');
            if ($listing->district_id) {
                $leads->where('district_id', $listing->district_id);
            }
            if ($listing->project_id) {
                $leads->where('project_id', $listing->project_id);
            }
            if ($listing->area) {
                $minArea = $area - 100;
                $maxArea = $area + 100;
                $leads->whereRaw('CAST(area AS DECIMAL(10, 2)) BETWEEN ? AND ?', [$minArea, $maxArea]);
            }
            if ($listing->price) {
                $minPrice = $price - 100000;
                $maxPrice = $price + 100000;
                $leads->whereRaw('CAST(price AS DECIMAL(10, 2)) BETWEEN ? AND ?', [$minPrice, $maxPrice]);
            }
            $listingList = $leads->where('type', 3);
            $datatable = Datatables::of($listingList);
            return collect($datatable->make(true)->getData());
        }
    }

    public function listingsSimpleList()
    {
        return Listing::all();
    }

    public function getListingDetail($id)
    {
        $item = Listing::with('project')->find($id);
        if ($item) {
            $item['features'] = explode(',', $item['features']);
            $item['contacts'] = explode(',', $item['contacts']);
            $item['gallery'] = $item['gallery'] ? json_decode($item['gallery'], true) : [];
            $item['listing_details'] = $item['listing_details'] ? json_decode($item['listing_details'], true) : [];
            return $item;
        }
    }

    public function getPublicListingDetail($id)
    {
        $item = Listing::with('project', 'purpose', 'property_type', 'unit_type', 'completion_status', 'rent_frequency', 'cheque', 'development_status', 'ownership_status', 'sale_status')->find($id);
        if (($item && $item->status == 1) || ($item && $item->added_by == Auth::id())) {
            $item['hk'] = $item->getHK();
            $fIds = explode(',', $item['features']);
            $item['fText'] = implode(', ', Attribute::whereIn('id', $fIds)->pluck('name')->toArray());
            $item['gallery'] = $item['gallery'] ? json_decode($item['gallery'], true) : [];
            return $item;
        }
    }

    public function uploadListingFile($uploadedFile)
    {
        return $this->uploadFileService->uploadPublicFile($uploadedFile, 'listing', 'listings');
    }

    public function uploadListingFiles($uploadedFiles)
    {
        return $this->uploadFileService->uploadPublicFiles($uploadedFiles, 'listing', 'listings');
    }

    public function deleteUploadedListingFile($data)
    {
        if ($data['image_id'] && $data['image_id'] !== '') {
            $tempPublicImageId = $data['image_id'];
            if (!empty($tempPublicImageId)) {
                $tempPublicImage = TempPublicImage::find($tempPublicImageId);
                if ($tempPublicImage) {
                    if (File::exists($tempPublicImage->absolute_path)) {
                        $tempPublicImage->delete();
                        File::delete($tempPublicImage->absolute_path);
                    }
                }
            }
        }
        if ($data['image_path'] && $data['image_path'] !== '') {
            $imagePath = $data['image_path'];
            if (!empty($imagePath)) {
                if (File::exists($imagePath)) {
                    $filename = explode('/', $imagePath);
                    $check1 = Listing::where('thumb_image', $data['image_path'])->first();
                    if ($check1)
                        $check1->update(['thumb_image' => null]);
                    $check2 = Listing::where('brochure', $data['image_path'])->first();
                    if ($check2)
                        $check2->update(['brochure' => null]);
                    $check3 = Listing::where('gallery', 'LIKE', '%' . $filename[2] . '%')->first();
                    if ($check3) {
                        $jsonArray = json_decode($check3->gallery, true);
                        $jsonArray = array_filter($jsonArray, function ($item) use ($imagePath) {
                            return $item['path'] !== $imagePath;
                        });
                        $jsonArray = array_values($jsonArray);
                        $check3->update(['gallery' => json_encode($jsonArray)]);
                    }
                    File::delete($imagePath);
                }
            }
        }
    }

    public function createListing($data)
    {
        $listing = new Listing();
        $listing->city_id = $data['city_id'] ?? null;
        $listing->developer_id = $data['developer_id'] ?? null;
        $listing->purpose_id = $data['purpose_id'] ?? null;
        $listing->unit_type_id = $data['unit_type_id'] ?? null;
        $listing->type = $data['type'] ?? null;
        if ($data['project_id']) {
            $pro = Attribute::find($data['project_id']);
            if ($pro && $pro->parent) {
                $listing->district_id = $pro->parent->id;
            }
            if ($pro && $pro->parent && $pro->parent->parent) {
                $listing->city_id = $pro->parent->parent->id;
            }
            $listing->project_id = $data['project_id'] ?? null;
        }
        if ($data['property_type_id']) {
            $attr = Attribute::find($data['property_type_id']);
            if ($attr && $attr->parent) {
                $listing->property_type_id = $data['property_type_id'];
                $listing->property_type_title = $attr->parent->name;
            }
        }
        $listing->completion_status_id = $data['completion_status_id'] ?? null;
        $listing->ownership_status_id = $data['ownership_status_id'] ?? null;
        $listing->development_status_id = $data['development_status_id'] ?? null;
        $listing->sale_status_id = $data['sale_status_id'] ?? null;
        $listing->rent_frequency_id = $data['rent_frequency_id'] ?? null;
        $listing->cheque_id = $data['cheque_id'] ?? null;
        $listing->title = $data['title'] ?? null;
        $listing->slug = Str::slug($data['title'], '-');
        $listing->full_desc = $data['full_desc'] ?? null;
        $listing->price = $data['price'] ?? null;
        $listing->area = $data['area'] ?? null;
        $listing->max_area = $data['max_area'] ?? null;
        $listing->beds = $data['beds'] ?? null;
        $listing->max_beds = $data['max_beds'] ?? null;
        $listing->baths = $data['baths'] ?? null;
        $listing->max_baths = $data['max_baths'] ?? null;
        $listing->lat = $data['lat'] ?? null;
        $listing->lng = $data['lng'] ?? null;
        $listing->project_completion_date = $data['pcd'] ?? null;
        // $listing->location = $data['location'] ?? null;
        $listing->meta_title = $data['meta_title'] ?? null;
        $listing->meta_keywords = $data['meta_keywords'] ?? null;
        $listing->meta_desc = $data['meta_desc'] ?? null;
        $listing->added_by = Auth::id();
        if (!empty($data['listing_features'])) {
            $listing->features = implode(',', $data['listing_features']);
        }
        if (!empty($data['listing_contacts'])) {
            $listing->contacts = implode(',', $data['listing_contacts']);
        }
        if (isset($data['thumb_image_id']) && $data['thumb_image_id']) {
            $image = NULL;
            $tempPublicImageId = $data['thumb_image_id'];
            $tempPublicImage = TempPublicImage::find($tempPublicImageId);
            if ($tempPublicImage) {
                if (File::exists($tempPublicImage->path)) {
                    $image = $tempPublicImage->path;
                }
                $tempPublicImage->delete();
            }
            $listing->thumb_image = $image;
        } else {
            $this->addErrors(['Thumbnail image is required']);
            return false;
        }
        if (isset($data['primary_image_id']) && $data['primary_image_id']) {
            $image = NULL;
            $tempPublicImageId = $data['primary_image_id'];
            $tempPublicImage = TempPublicImage::find($tempPublicImageId);
            if ($tempPublicImage) {
                if (File::exists($tempPublicImage->path)) {
                    $image = $tempPublicImage->path;
                }
                $tempPublicImage->delete();
            }
            $listing->brochure = $image;
        }
        if (!empty($data['gallery_images'])) {
            $garr = [];
            foreach ($data['gallery_images'] as $img) {
                $fimg['sort_order'] = $img['sort_order'];
                $fimg['path'] = $img['path'];
                // $fimg['url'] = $img['url'];
                $garr[] = $fimg;
            }
            $listing->gallery = json_encode($garr);
        }
        if (!empty($data['listing_details'])) {
            $larr = [];
            foreach ($data['listing_details'] as $ld) {
                if ($ld['title'] && $ld['price'] && $ld['minBeds'] && $ld['maxBeds'] && $ld['minArea'] && $ld['maxArea']) {
                    $fld['title'] = $ld['title'];
                    $fld['price'] = $ld['price'];
                    $fld['minBeds'] = $ld['minBeds'];
                    $fld['maxBeds'] = $ld['maxBeds'];
                    $fld['minArea'] = $ld['minArea'];
                    $fld['maxArea'] = $ld['maxArea'];
                    $larr[] = $fld;
                }
            }
            $listing->listing_details = json_encode($larr);
        }
        $listing->save();
        $listing->update(['p_id' => generatePin($listing->id)]);
    }

    public function updateListing($data, $id)
    {
        $listing = Listing::findOrFail($id);
        if (auth()->user()->type == 1 || $listing->added_by == auth()->id()) {
            $listing->city_id = $data['city_id'] ?? null;
            $listing->purpose_id = $data['purpose_id'] ?? null;
            if ($data['project_id']) {
                $pro = Attribute::find($data['project_id']);
                if ($pro && $pro->parent) {
                    $listing->district_id = $pro->parent->id;
                }
                if ($pro && $pro->parent && $pro->parent->parent) {
                    $listing->city_id = $pro->parent->parent->id;
                }
                $listing->project_id = $data['project_id'] ?? null;
            }
            if ($data['property_type_id']) {
                $attr = Attribute::find($data['property_type_id']);
                if ($attr && $attr->parent) {
                    $listing->property_type_id = $data['property_type_id'];
                    $listing->property_type_title = $attr->parent->name;
                }
            }
            $listing->completion_status_id = $data['completion_status_id'] ?? null;
            $listing->ownership_status_id = $data['ownership_status_id'] ?? null;
            $listing->rent_frequency_id = $data['rent_frequency_id'] ?? null;
            $listing->cheque_id = $data['cheque_id'] ?? null;
            $listing->development_status_id = $data['development_status_id'] ?? null;
            $listing->sale_status_id = $data['sale_status_id'] ?? null;
            $listing->developer_id = $data['developer_id'] ?? null;
            $listing->unit_type_id = $data['unit_type_id'] ?? null;
            $listing->title = $data['title'] ?? null;
            $listing->slug = Str::slug($data['title'], '-');
            $listing->short_desc = $data['short_desc'] ?? null;
            $listing->full_desc = $data['full_desc'] ?? null;
            $listing->price = $data['price'] ?? null;
            $listing->area = $data['area'] ?? null;
            $listing->max_area = $data['max_area'] ?? null;
            $listing->beds = $data['beds'] ?? null;
            $listing->max_beds = $data['max_beds'] ?? null;
            $listing->baths = $data['baths'] ?? null;
            $listing->max_baths = $data['max_baths'] ?? null;
            $listing->lat = $data['lat'] ?? null;
            $listing->lng = $data['lng'] ?? null;
            $listing->project_completion_date = $data['pcd'] ?? null;
            $listing->location = $data['location'] ?? null;
            $listing->meta_title = $data['meta_title'] ?? null;
            $listing->meta_keywords = $data['meta_keywords'] ?? null;
            $listing->meta_desc = $data['meta_desc'] ?? null;
            $listing->updated_by = Auth::id();
            $listing->features = !empty($data['listing_features']) ? implode(',', $data['listing_features']) : null;
            $listing->contacts = !empty($data['listing_contacts']) ? implode(',', $data['listing_contacts']) : null;
            if (isset($data['thumb_image_id']) && $data['thumb_image_id'] !== '') {
                $timage = '';
                $tempPublicImageId = $data['thumb_image_id'];
                $tempPublicImage = TempPublicImage::find($tempPublicImageId);
                if ($tempPublicImage) {
                    if (File::exists($tempPublicImage->path)) {
                        $timage = $tempPublicImage->path;
                    }
                    $tempPublicImage->delete();
                }
                $listing->thumb_image = $timage;
            }
            if (isset($data['primary_image_id']) && $data['primary_image_id'] !== '') {
                $timage = '';
                $tempPublicImageId = $data['primary_image_id'];
                $tempPublicImage = TempPublicImage::find($tempPublicImageId);
                if ($tempPublicImage) {
                    if (File::exists($tempPublicImage->path)) {
                        $timage = $tempPublicImage->path;
                    }
                    $tempPublicImage->delete();
                }
                $listing->brochure = $timage;
            }
            if (!empty($data['gallery_images'])) {
                $garr = [];
                foreach ($data['gallery_images'] as $img) {
                    $fimg['sort_order'] = $img['sort_order'];
                    $fimg['path'] = $img['path'];
                    $garr[] = $fimg;
                }
                $listing->gallery = json_encode($garr);
            }
            if (!empty($data['listing_details'])) {
                $larr = [];
                foreach ($data['listing_details'] as $ld) {
                    if ($ld['title'] && $ld['price'] && $ld['minBeds'] && $ld['maxBeds'] && $ld['minArea'] && $ld['maxArea']) {
                        $fld['title'] = $ld['title'];
                        $fld['price'] = $ld['price'];
                        $fld['minBeds'] = $ld['minBeds'];
                        $fld['maxBeds'] = $ld['maxBeds'];
                        $fld['minArea'] = $ld['minArea'];
                        $fld['maxArea'] = $ld['maxArea'];
                        $larr[] = $fld;
                    }
                }
                $listing->listing_details = json_encode($larr);
            }
            $listing->save();
        }
    }
}
