<?php
namespace App\Controllers;

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

class LandingController extends Controller
{
    private PropertyModel $propertyModel;

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

    private function getContent(): array
    {
        $rows = $this->db->fetchAll("SELECT s.key, s.value FROM settings s WHERE s.group='content'");
        return array_column($rows, 'value', 'key');
    }

    public function index(): void
    {
        $featured    = $this->propertyModel->getFeatured(6);
        $types       = $this->db->fetchAll("SELECT * FROM property_types ORDER BY id");
        $testimonials = $this->db->fetchAll("SELECT * FROM testimonials WHERE is_active=1 ORDER BY id LIMIT 6");
        $news        = $this->db->fetchAll("SELECT n.*, u.first_name, u.last_name FROM news n LEFT JOIN users u ON u.id=n.author_id WHERE n.is_published=1 ORDER BY n.published_at DESC LIMIT 3");
        $faqs        = $this->db->fetchAll("SELECT * FROM faqs WHERE is_active=1 ORDER BY sort_order LIMIT 8");
        $stats = [
            'properties' => $this->db->fetchColumn("SELECT COUNT(*) FROM properties WHERE status='active'"),
            'tenants'    => $this->db->fetchColumn("SELECT COUNT(*) FROM tenants WHERE status='active'"),
            'units'      => $this->db->fetchColumn("SELECT COUNT(*) FROM units WHERE status='available'"),
            'regions'    => $this->db->fetchColumn("SELECT COUNT(DISTINCT region_id) FROM properties"),
        ];
        $regions = $this->db->fetchAll("SELECT r.*, COUNT(p.id) AS prop_count FROM regions r LEFT JOIN properties p ON p.region_id=r.id GROUP BY r.id HAVING prop_count > 0 ORDER BY prop_count DESC LIMIT 6");

        $content = $this->getContent();
        $this->view('landing.home', compact('featured','types','testimonials','news','faqs','stats','regions','content') + ['title' => 'Zabibu Residence - Find Your Perfect Home in Tanzania']);
    }

    public function about(): void
    {
        $content = $this->getContent();
        $this->view('landing.about', compact('content') + ['title' => 'About Us - Zabibu Residence']);
    }

    public function residences(): void
    {
        $types   = $this->db->fetchAll("SELECT * FROM property_types ORDER BY id");
        $regions = $this->db->fetchAll("SELECT * FROM regions ORDER BY name");

        $filters = [
            'type_id'   => $_GET['type']   ?? '',
            'region_id' => $_GET['region'] ?? '',
        ];

        $all        = $this->propertyModel->allWithDetails(array_filter($filters));
        $perPage    = 12;
        $page       = max(1, (int)($_GET['page'] ?? 1));
        $total      = count($all);
        $totalPages = (int)ceil($total / $perPage);
        $properties = array_slice($all, ($page - 1) * $perPage, $perPage);

        $pagination = [
            'page'       => $page,
            'perPage'    => $perPage,
            'total'      => $total,
            'totalPages' => $totalPages,
        ];

        $this->view('landing.residences', compact('properties','types','regions','pagination') + ['title' => 'All Residences - Zabibu Residence']);
    }

    public function show(string $id): void
    {
        $property = $this->propertyModel->findWithDetails((int)$id);
        if (!$property) { $this->abort(404); return; }
        $images    = $this->propertyModel->getImages((int)$id);
        $amenities = $this->propertyModel->getAmenities((int)$id);
        $units     = $this->propertyModel->getUnits((int)$id);
        $related   = $this->propertyModel->getFeatured(3);

        $rents   = array_column($units, 'monthly_rent');
        $minRent = !empty($rents) ? min($rents) : 0;

        $this->view('landing.property-detail', compact('property','images','amenities','units','related','minRent') + ['title' => $property['name'] . ' - Zabibu Residence']);
    }

    public function search(): 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'] ?? '',
            'has_parking' => $_GET['has_parking'] ?? '',
            'keyword'     => $_GET['keyword'] ?? '',
        ];
        $properties = $this->propertyModel->search(array_filter($filters));
        $types   = $this->db->fetchAll("SELECT * FROM property_types ORDER BY id");
        $regions = $this->db->fetchAll("SELECT * FROM regions ORDER BY name");
        $this->view('landing.search', compact('properties','filters','types','regions') + ['title' => 'Search Properties - Zabibu Residence']);
    }

    public function contact(): void
    {
        $content = $this->getContent();
        $this->view('landing.contact', compact('content') + ['title' => 'Contact Us - Zabibu Residence']);
    }

    public function sendContact(): void
    {
        Helper::setFlash('success', 'Thank you! Your message has been received. We will respond within 24 hours.');
        $this->redirect(APP_URL . '/contact');
    }

    public function newsletter(): void
    {
        $email = filter_var($this->input('email',''), FILTER_SANITIZE_EMAIL);
        if ($email && filter_var($email, FILTER_VALIDATE_EMAIL)) {
            try {
                $this->db->insert('newsletter_subscribers', ['email' => $email, 'status' => 'active']);
                Helper::setFlash('success', 'Thank you for subscribing to our newsletter!');
            } catch (\Exception $e) {
                Helper::setFlash('info', 'You are already subscribed!');
            }
        }
        $this->back();
    }
}
