<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Http;
use App\Http\Controllers\Api\PropertyApiController;
use Illuminate\Pagination\LengthAwarePaginator;
use App\Models\Property;
use App\Models\Address;
use App\Models\Detail;

use Illuminate\Http\Request;

class FrontendController extends Controller
{

    public function Home()
    {
        // Call the summary API
        $response = app(\App\Http\Controllers\Api\PropertyApiController::class)->summary();
        $api = $response->getData(true); 
        $data = $api['data']; // summary data

        // Call the /api endpoint to get categories that have data
        $categoryResponse = app(\App\Http\Controllers\Api\PropertyApiController::class)->getAllCategories();
        $categoryData = $categoryResponse->getData(true);
        $categories = $categoryData['data'] ?? []; // Only categories that have posts

        // Load properties for those categories
        $allProperties = [];
        foreach ($categories as $category) {
            $categoryResponse = app(\App\Http\Controllers\Api\PropertyApiController::class)->getByCategory($category);
            $categoryData = $categoryResponse->getData(true);
            if (isset($categoryData['data']) && is_array($categoryData['data'])) {
                $allProperties = array_merge($allProperties, $categoryData['data']);
            }
        }

        return view('frontend.page.home', compact('data', 'allProperties', 'categories'));
    }


    // public function Buy($category){
    //     $validCategories = ['sell', 'rent', 'lease'];

    //     if (!in_array(strtolower($category), $validCategories)) {
    //         abort(404); 
    //     }

    //     $controller = app(\App\Http\Controllers\Api\PropertyApiController::class);
    //     $properties = $controller->getByCategory($category)->getData(true)['data'];

    //     return view('frontend.page.category', [
    //         'category' => $category,
    //         'properties' => $properties,
    //     ]);
    // }

    public function Buy($category)
    {
        $allowedCategories = Property::select('category_name')
            ->distinct()
            ->pluck('category_name')
            ->map(fn($c) => strtolower($c))
            ->toArray();

        if (!in_array(strtolower($category), $allowedCategories)) {
            abort(404);
        }
        $apiResponse = app(\App\Http\Controllers\Api\PropertyApiController::class)
                        ->getByCategory($category);
        $responseData = $apiResponse->getData(true); 

        // Safety check
        if (!isset($responseData['data'], $responseData['pagination'])) {
            abort(500, 'Invalid API response structure.');
        }

        // Recreate paginator from API data
        $properties = new LengthAwarePaginator(
            $responseData['data'],                         
            $responseData['pagination']['total'],         
            $responseData['pagination']['per_page'],     
            $responseData['pagination']['current_page'],   
            [
                'path' => request()->url(),
                'query' => request()->query(),
            ]
        );

        return view('frontend.page.category', [
            'category' => $category,
            'properties' => $properties,
        ]);
    }

    public function PropertyDetails($category, $slug)
    {
        $response = app(\App\Http\Controllers\Api\PropertyApiController::class)
            ->showByCategoryAndSlug($category, $slug);

        //$property = $response->getData(true)['data'];
        $responseData = $response->getData(true);
        $property = $responseData['data'] ?? null;

        if (!$property) {
            abort(404); 
        }

        $categoryResponse = app(\App\Http\Controllers\Api\PropertyApiController::class)
            ->getByCategory($category);
        $allSameCategory = $categoryResponse->getData(true)['data'] ?? [];

        $similarProperties = collect($allSameCategory)->filter(function ($item) use ($property) {
            return $item['id'] !== $property['id'];
        })->take(6); 

        return view('frontend.page.property-details', compact('property', 'similarProperties', 'category'));
    }

    public function Contact()
    {
       return view('frontend.page.contact');
    }
    public function About(){
        return view('frontend.page.about');
    }


public function search(Request $request)
{
    $category = $request->input('propertyMode'); // get input from URL/query
    $apiResponse = app(PropertyApiController::class)->getByCategory($category);
    $responseData = $apiResponse->getData(true);

    if (!$responseData['status'] || !isset($responseData['data'])) {
        return view('frontend.page.results', [
            'properties' => [],
            'error' => $responseData['message'] ?? 'No properties found.'
        ]);
    }

    // Convert array to paginator
    $properties = new LengthAwarePaginator(
        $responseData['data'],
        $responseData['pagination']['total'],
        $responseData['pagination']['per_page'],
        $responseData['pagination']['current_page'],
        [
            'path' => request()->url(),
            'query' => request()->query(),
        ]
    );

    return view('frontend.page.results', [
        'properties' => $properties,
        'category' => $category,
    ]);
}


}
