<?php

namespace App\Services;

use App\Models\Rental;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use Exception;

class BuildiumSyncService
{
    private $sourceUrl = "https://bridgerproperties.managebuilding.com/Resident/public/rentals";
    private $baseUrl = "https://bridgerproperties.managebuilding.com";

    public function sync()
    {
        Log::info("Buildium sync started.");

        try {
            $response = Http::withHeaders([
                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
            ])->get($this->sourceUrl);

            if ($response->failed()) {
                throw new Exception("Failed to fetch HTML. HTTP Status: " . $response->status());
            }

            $html = $response->body();
            $rentalsData = $this->parseHtml($html);

            foreach ($rentalsData as $data) {
                $this->updateOrCreateRental($data);
            }

            Log::info("Buildium sync completed. Processed " . count($rentalsData) . " rentals.");
            return count($rentalsData);

        } catch (Exception $e) {
            Log::error("Buildium sync failed: " . $e->getMessage());
            throw $e;
        }
    }

    private function parseHtml($html)
    {
        $rentals = [];
        preg_match_all('/<a class="featured-listing[^>]*>(.*?)<\/a>/s', $html, $matches);

        foreach ($matches[0] as $block) {
            $rental = [];
            
            preg_match('/data-bedrooms="([^"]*)"/', $block, $attr);
            $rental['bedrooms'] = (float)($attr[1] ?? 0);
            
            preg_match('/data-bathrooms="([^"]*)"/', $block, $attr);
            $rental['bathrooms'] = (float)($attr[1] ?? 0);
            
            preg_match('/data-rent="([^"]*)"/', $block, $attr);
            $rental['rent'] = (float)($attr[1] ?? 0);
            
            preg_match('/data-square-feet="([^"]*)"/', $block, $attr);
            $rental['square_feet'] = (int)($attr[1] ?? 0);
            
            preg_match('/href="\/Resident\/public\/rentals\/(\d+)"/', $block, $attr);
            $rental['listing_id'] = (int)($attr[1] ?? 0);

            // Image handling
            preg_match('/src="([^"]*)"/', $block, $attr);
            $imgUrl = $attr[1] ?? '';
            if ($imgUrl) {
                if (strpos($imgUrl, 'http') !== 0) {
                    $imgUrl = $this->baseUrl . (strpos($imgUrl, '/') === 0 ? '' : '/') . html_entity_decode($imgUrl);
                }
                $rental['main_image_url'] = $this->downloadImage($imgUrl, $rental['listing_id']);
            }

            // Address
            preg_match('/<div class="address[^>]*>(.*?)<\/div>/s', $block, $attr);
            $addressHtml = $attr[1] ?? '';
            $rental['address'] = trim(strip_tags($addressHtml));
            
            if (empty($rental['address'])) {
                preg_match('/<h3>(.*?)<\/h3>/s', $block, $attr);
                $rental['address'] = trim(strip_tags($attr[1] ?? ''));
            }

            // Property Name (Targeting the building-name class)
            preg_match('/class="details__building-name[^>]*">(.*?)<\//s', $block, $attr);
            $rental['property_name'] = trim(strip_tags($attr[1] ?? ''));
            
            // Available Date (Parse into D M Y)
            if (preg_match('/available\s+([A-Za-z]+)\s+(\d+)/i', $block, $attr)) {
                try {
                    $dateStr = $attr[1] . ' ' . $attr[2];
                    $date = \Carbon\Carbon::parse($dateStr);
                    // If the date is in the past, it's likely for next year
                    if ($date->isPast() && $date->diffInMonths(now()) > 6) {
                        $date->addYear();
                    }
                    $rental['available_date'] = $date->format('j F Y'); // e.g. "22 May 2026"
                } catch (\Exception $e) {
                    $rental['available_date'] = trim($attr[0]);
                }
            }

            // Location data
            preg_match('/data-location="([^"]*)"/', $block, $attr);
            if (!empty($attr[1])) {
                $locParts = explode(',', $attr[1]);
                $rental['city'] = trim($locParts[0] ?? '');
                if (isset($locParts[1])) {
                    $stateZip = explode('|', $locParts[1]);
                    $rental['state'] = trim($stateZip[0] ?? '');
                    $rental['zip_code'] = trim($stateZip[1] ?? '');
                }
            }

            $rentals[] = $rental;
        }

        return $rentals;
    }

    private function downloadImage($url, $id)
    {
        try {
            $response = Http::get($url);
            if ($response->successful()) {
                $filename = "rentals/listing_{$id}.jpg";
                Storage::disk('public')->put($filename, $response->body());
                // Return full absolute URL including environment base URL
                return url('storage/' . $filename);
            }
        } catch (Exception $e) {
            Log::warning("Failed to download image for listing $id: " . $e->getMessage());
        }
        return null;
    }

    private function updateOrCreateRental($data)
    {
        Rental::updateOrCreate(
            ['listing_id' => $data['listing_id']],
            array_merge($data, ['last_synced_at' => now()])
        );
    }
}
