<?php
namespace App\Controllers\Api;

use Core\Controller;
use App\Models\PropertyModel;

class PropertyApiController extends Controller
{
    private PropertyModel $model;

    public function __construct()
    {
        parent::__construct();
        $this->model = new PropertyModel();
    }

    public function index(): void
    {
        $filters = [
            'region_id'    => $_GET['region_id']    ?? '',
            'district_id'  => $_GET['district_id']  ?? '',
            'type_id'      => $_GET['type_id']       ?? '',
            'bedrooms'     => $_GET['bedrooms']      ?? '',
            'min_price'    => $_GET['min_price']     ?? '',
            'max_price'    => $_GET['max_price']     ?? '',
            'is_furnished' => $_GET['is_furnished']  ?? '',
            'keyword'      => $_GET['keyword']       ?? '',
        ];
        $page    = max(1, (int)($_GET['page'] ?? 1));
        $perPage = min(50, (int)($_GET['per_page'] ?? 12));

        $properties = $this->model->search(array_filter($filters));
        $total      = count($properties);
        $items      = array_slice($properties, ($page - 1) * $perPage, $perPage);

        $this->json([
            'success' => true,
            'data'    => $items,
            'meta'    => ['total' => $total, 'page' => $page, 'per_page' => $perPage, 'pages' => ceil($total / $perPage)],
        ]);
    }

    public function show(string $id): void
    {
        $property = $this->model->findWithDetails((int)$id);
        if (!$property) { $this->json(['success' => false, 'message' => 'Property not found.'], 404); return; }

        $property['images']    = $this->model->getImages((int)$id);
        $property['amenities'] = $this->model->getAmenities((int)$id);
        $property['units']     = $this->model->getUnits((int)$id);

        $this->json(['success' => true, 'data' => $property]);
    }

    public function featured(): void
    {
        $limit = min(20, (int)($_GET['limit'] ?? 6));
        $this->json(['success' => true, 'data' => $this->model->getFeatured($limit)]);
    }

    public function regions(): void
    {
        $regions = $this->db->fetchAll("SELECT r.*, COUNT(DISTINCT p.id) AS property_count FROM regions r LEFT JOIN properties p ON p.region_id=r.id GROUP BY r.id ORDER BY r.name");
        $this->json(['success' => true, 'data' => $regions]);
    }

    public function regionDistricts(string $regionId): void
    {
        $districts = $this->db->fetchAll("SELECT * FROM districts WHERE region_id=? ORDER BY name", [$regionId]);
        $this->json(['success' => true, 'data' => $districts]);
    }

    public function districtWards(string $districtId): void
    {
        $wards = $this->db->fetchAll("SELECT * FROM wards WHERE district_id=? ORDER BY name", [$districtId]);
        $this->json(['success' => true, 'data' => $wards]);
    }
}
