<?php

namespace App\Http\Controllers;

use App\Models\BannerHome;
use App\Models\City;
use App\Models\ColumnsSectionTwo;
use App\Models\TextSectionTwo;
use App\Models\TextSectionthree;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use GuzzleHttp\Cookie\CookieJar;
use App\Models\SectionFourLeft;
use App\Models\SectionFourRight;
use App\Models\SectionFourTitle;
use App\Models\Property;
use App\Models\TypeProperty;

//use GuzzleHttp\Psr7\HttpFactory;


class WelcomeController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        
        //$page = request("page",1);
        //$pagesize = request("page_size",6);
        /*$response = Http::timeout(30)
            ->withHeaders([
                "apikey" => config('services.fr_api.key'),  // desde .env
                'x-api-key' => config('services.fr_api.key'),   // desde .env
                'Accept'    => 'application/json',
            ])
            ->withOptions([          // <-- cookie real
                'cookies' => CookieJar::fromArray([
                    'cookie' => config('services.fr_api.cookie'),
                ], 'kong-qa.frcol.io')
            ])
            ->get(config('services.fr_api.url') . 'listing', [
                'page'      => request('page', 1),
                'page_size' => request('page_size', 6),
            ]);
                
        $baseItems = collect($response->json('results', []))->shuffle();

        $items = $baseItems->map(function ($inmueble) {
            // Segundo request por cada id
            $detail = Http::timeout(15)
                ->withHeaders([
                    "apikey" => config('services.fr_api.key'),  // desde .env
                    'x-api-key' => config('services.fr_api.key'),
                    'Accept'    => 'application/json',
                ])
                ->withOptions([
                    'cookies' => CookieJar::fromArray([
                        'cookie' => config('services.fr_api.cookie'),
                    ], 'kong-qa.frcol.io')
                ])
                ->get(config('services.fr_api.url') . 'listing/' . $inmueble['id'] )
                ->json();   // array con price, photos, etc.

            // fusionamos ambos arrays
            return array_merge($inmueble, [
                'offer'=> $detail['offer'] ?? null,
                'property_type'  => $detail['property_type']  ?? null,
                'area' => $detail['area'] ?? null,
                'bedrooms'=> $detail['bedrooms'] ?? null,
                'baths'=> $detail['baths'] ?? null,
                'garages'=> $detail['garages'] ?? null,
                'photos' => $detail['photos'] ?? [],
                'administration' => $detail['administration'] ?? null,
                'price' => $detail['price'] ?? null,
                'address' => $detail['address'] ?? null,
            ]);
        });*/

        $banner = BannerHome::first();
        $text = TextSectionTwo::first();
        $column = ColumnsSectionTwo::all();
        $left = SectionFourLeft::first();
        $textt = TextSectionthree::first();
        $title = SectionFourTitle::first();
        $right = SectionFourRight::all();
        $great = Property::where('state', 'Activo')
                    ->where('property_status_id', 4)
                    ->inRandomOrder()
                    ->limit(6)
                    ->get();
        $types  = TypeProperty::all();
        $cities = City::orderBy('name')->get();

        return view('welcome', compact(
            'banner', 'text', 'column', 'textt',
            'left', 'title', 'right', 'great',
            'types', 'cities'
        ));
    }  

    public function search(Request $request)
    {
        // Redirige según el tipo seleccionado
        $params = $request->only(['type_property', 'city']);

        if ($request->offer === 'rent') {
            return redirect()->route('rent', $params);
        }

        return redirect()->route('sale', $params);
    }
      
    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        $property = Property::with(['images', 'typeProperty', 'offer', 'internalCharacteristics', 'externalCharacteristics'])->findOrFail($id);
    
        return view('property-detail', compact('property'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
