<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;

class PropertyController extends Controller
{
    protected $lang;


    /**
     * Detect language from URL path
     */
    protected function detectLanguageFromUrl()
    {
        $uri = request()->path();

        if (strpos($uri, 'search') !== false) {
            $this->lang = 'en';
        } elseif (strpos($uri, 'pretraga') !== false) {
            $this->lang = 'hr';
        } elseif (strpos($uri, 'property') !== false) {
            $this->lang = 'en';
        } elseif (strpos($uri, 'nekretnina') !== false) {
            $this->lang = 'hr';
        }else{
            $this->lang = 'hr';
        }

        App::setLocale($this->lang);
    }

    /**
     * Search for properties
     *
     * @param Request $request
     * @param string|null $params
     * @return \Illuminate\View\View|\Illuminate\Http\RedirectResponse
     */
    public function search(Request $request)
    {
        $location = $request->input('location') ?? null;
        $type = $request->input('type') ?? null;
        $search_query = $request->input('query') ?? null;
        $locale = app()->getLocale();
    
        // Build database query
        $properties = DB::table('baza_realestate as r')
            ->join('baza_realestate_web as w', 'r.id', '=', 'w.realestate_id')
            ->join('baza_locations_all as l', 'r.location', '=', 'l.id')
            ->join('baza_locations_main as lm', 'l.location_main_id', '=', 'lm.id')
            ->join('baza_realestate_types as t', function ($join) {
                $join->whereRaw("CONCAT(';', r.type_code, ';') LIKE CONCAT('%;', t.type_code, ';%')");
            })
            ->select(
                'r.id',
                'r.company_id',
                'r.bedrooms',
                'r.bathrooms',
                'r.parking',
                'r.terraces',
                'r.area',
                'r.price',
                'w.order',
                "w.name_{$locale} as title",
                "w.description_{$locale} as description",
                "w.alias_{$locale} as alias",
                "l.hr as location_name"
            )
            ->where('w.active', 1)
            ->when($location, function ($query) use ($location, $locale) {
                $location = Str::title(str_replace('-', ' ', $location));
                $query->where("lm.{$locale}", $location);
            })
            ->when($type, function ($query) use ($type, $locale) {
                $type = Str::title(str_replace('-', ' ', $type));
                $query->where("t.{$locale}", 'LIKE', "%{$type}%");
            })
            ->when($search_query, function ($query) use ($search_query, $locale) {
                $query->where(function($q) use ($search_query, $locale) {
                    $q->where("w.name_{$locale}", 'LIKE', "%{$search_query}%")
                      ->orWhere("w.description_{$locale}", 'LIKE', "%{$search_query}%");
                });
            })
            ->groupBy('r.id', 'r.company_id', 'r.bedrooms', 'r.bathrooms', 'r.parking', 'r.terraces', 'r.area', 'r.price', "w.name_{$locale}", "w.description_{$locale}", "w.alias_{$locale}", "w.order","l.hr")
            ->orderBy('w.order', 'ASC')
            ->paginate(16);


        return view('search', [
            'location' => $location,
            'type' => $type,
            'search_query' => $search_query,
            'properties' => $properties,
        ]);
    }

    /**
     * View a single property
     *
     * @param string $alias
     * @return \Illuminate\View\View|\Illuminate\Http\RedirectResponse
     */
    public function view($alias)
    {
        $this->detectLanguageFromUrl();
        $locale = $this->lang;

        // Build database query for single property
        $property = DB::table('baza_realestate as r')
            ->join('baza_realestate_web as w', 'r.id', '=', 'w.realestate_id')
            ->join('baza_locations_all as l', 'r.location', '=', 'l.id')
            ->join('baza_locations_main as lm', 'l.location_main_id', '=', 'lm.id')
            ->select(
                'r.id',
                'r.company_id',
                'r.bedrooms',
                'r.bathrooms',
                'r.parking',
                'r.terraces',
                'r.area',
                'r.price',
                'r.type_code',
                'r.land_area',
                'r.view',
                'r.youtube_link',
                "w.name_{$locale} as title",
                "w.description_{$locale} as description",
                "w.alias_{$locale} as alias",
                "l.hr as location_name",
                "lm.{$locale} as location_main"
            )
            ->where("w.alias_{$locale}", $alias)
            ->where('w.active', 1)
            ->first();

        // If property not found, redirect to search page
        if (!$property) {
            return redirect()->route($locale === 'en' ? 'search.en' : 'search.hr')
                ->with('error', __('Property not found'));
        }


        //property types
        $property_type_codes = explode(';', $property->type_code);
        $propertyTypes = DB::table('baza_realestate_types')
            ->whereIn('type_code', $property_type_codes)
            ->select("{$locale} as type_name", "type")
            ->get();
        $property->type_name = $propertyTypes->pluck('type_name')->implode(', ');

        // Get similar properties based on type and location
        $similarProperties = DB::table('baza_realestate as r')
            ->join('baza_realestate_web as w', 'r.id', '=', 'w.realestate_id')
            ->join('baza_locations_all as l', 'r.location', '=', 'l.id')
            ->join('baza_locations_main as lm', 'l.location_main_id', '=', 'lm.id')
            ->select(
                'r.id',
                'r.company_id',
                'r.bedrooms',
                'r.bathrooms',
                'r.area',
                'r.price',
                "w.name_{$locale} as title",
                "w.alias_{$locale} as alias"
            )
            ->where('r.id', '!=', $property->id)
            ->where('r.type_code', 'LIKE', '%' . substr($property->type_code, 0, 1) . '%')
            ->where('w.active', 1)
            ->limit(6)
            ->get();

        return view('property', [
            'property' => $property,
            'similarProperties' => $similarProperties,
        ]);
    }

    /**
     * Handle property contact form submission
     *
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function contactProperty(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'phone' => 'required|string|max:255',
            'message' => 'required|string',
            'property_id' => 'required|integer',
            'property_title' => 'required|string'
        ]);

        // Get property and company details
        $property = DB::table('baza_realestate as r')
            ->join('baza_company as c', 'r.company_id', '=', 'c.id')
            ->select('r.id', 'r.company_id', 'c.name as company_name')
            ->where('r.id', $validated['property_id'])
            ->first();

        if (!$property) {
            return redirect()->back()
                ->with('error', __('app.property_not_found'))
                ->withInput();
        }

        // Prepare email data
        $emailData = [
            'name' => $validated['name'],
            'email' => $validated['email'],
            'phone' => $validated['phone'],
            'inquiry_message' => $validated['message'],
            'property_title' => $validated['property_title'],
            'property_id' => $validated['property_id'],
        ];

        // Send email to company
        try {
            Mail::send('emails.property-inquiry', $emailData, function ($message) use ($property, $emailData) {
                $message->to($property->company_email ?? 'info@imbnekretnine.hr')
                    ->subject('Property Inquiry: ' . $emailData['property_title'])
                    ->replyTo($emailData['email'], $emailData['name']);
            });

            return redirect()->back()
                ->with('success', __('app.property_contact_success'));
        } catch (\Exception $e) {
           
            return redirect()->back()
                ->with('error', __('app.contact_error'))
                ->withInput();
        }
    }
}
