<?php
namespace App\Controllers;

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

class PropertyController extends Controller
{
    private PropertyModel $model;

    public function __construct()
    {
        parent::__construct();
        $this->requireRole(['super_admin','property_owner','property_manager']);
        $this->model = new PropertyModel();
    }

    public function index(): void
    {
        $properties = $this->model->allWithDetails();
        $this->adminView('property.index', compact('properties') + ['title' => 'Properties', 'breadcrumb' => [['label'=>'Properties']]]);
    }

    public function create(): void
    {
        $types   = $this->db->fetchAll("SELECT * FROM property_types ORDER BY name");
        $regions = $this->db->fetchAll("SELECT * FROM regions ORDER BY name");
        $owners  = $this->db->fetchAll("SELECT id, CONCAT(first_name,' ',last_name) AS name FROM users WHERE role_id IN (1,2) ORDER BY first_name");
        $managers = $this->db->fetchAll("SELECT id, CONCAT(first_name,' ',last_name) AS name FROM users WHERE role_id IN (1,2,3) ORDER BY first_name");
        $amenities = $this->db->fetchAll("SELECT * FROM amenities ORDER BY category, name");
        $this->adminView('property.form', compact('types','regions','owners','managers','amenities') + ['title'=>'Add Property','property'=>null]);
    }

    public function store(): void
    {
        $this->verifyCsrf();
        $data = [
            'owner_id'         => $this->input('owner_id') ?: null,
            'manager_id'       => $this->input('manager_id') ?: null,
            'property_type_id' => $this->input('property_type_id') ?: null,
            'property_code'    => strtoupper(Helper::sanitize($this->input('property_code',''))),
            'name'             => Helper::sanitize($this->input('name','')),
            'slug'             => Helper::slug($this->input('name','')),
            'description'      => $this->input('description',''),
            'address'          => Helper::sanitize($this->input('address','')),
            'region_id'        => $this->input('region_id') ?: null,
            'district_id'      => $this->input('district_id') ?: null,
            'ward_id'          => $this->input('ward_id') ?: null,
            'area'             => Helper::sanitize($this->input('area','')),
            'latitude'         => $this->input('latitude') ?: null,
            'longitude'        => $this->input('longitude') ?: null,
            'total_floors'     => (int)$this->input('total_floors', 1),
            'year_built'       => $this->input('year_built') ?: null,
            'is_featured'      => $this->input('is_featured') ? 1 : 0,
            'status'           => $this->input('status','active'),
            'meta_title'       => Helper::sanitize($this->input('meta_title','')),
            'meta_description' => Helper::sanitize($this->input('meta_description','')),
        ];

        // Handle featured image upload
        if (!empty($_FILES['featured_image']['name'])) {
            $path = Helper::uploadFile($_FILES['featured_image'], 'properties', ALLOWED_IMAGE_TYPES);
            if ($path) $data['featured_image'] = $path;
        }

        try {
            $id = $this->model->create($data);
            // Save amenities
            $amenities = $_POST['amenities'] ?? [];
            foreach ($amenities as $amenityId) {
                $this->db->insert('property_amenities', ['property_id' => $id, 'amenity_id' => $amenityId]);
            }
            Helper::setFlash('success', 'Property created successfully.');
            $this->redirect(APP_URL . '/admin/properties');
        } catch (\Exception $e) {
            Helper::setFlash('danger', 'Error: ' . $e->getMessage());
            $this->back();
        }
    }

    public function show(string $id): void
    {
        $property  = $this->model->findWithDetails((int)$id);
        if (!$property) { $this->abort(404); return; }
        $images    = $this->model->getImages((int)$id);
        $amenities = $this->model->getAmenities((int)$id);
        $units     = $this->model->getUnits((int)$id);
        $buildings = $this->db->fetchAll("SELECT * FROM buildings WHERE property_id=?", [$id]);
        $stats = [
            'total_units'    => count($units),
            'occupied'       => count(array_filter($units, fn($u) => $u['status'] === 'occupied')),
            'available'      => count(array_filter($units, fn($u) => $u['status'] === 'available')),
            'monthly_income' => array_sum(array_map(fn($u) => $u['status']==='occupied'?$u['monthly_rent']:0, $units)),
        ];
        $this->adminView('property.show', compact('property','images','amenities','units','buildings','stats') + ['title' => $property['name']]);
    }

    public function edit(string $id): void
    {
        $property   = $this->model->find((int)$id);
        if (!$property) { $this->abort(404); return; }
        $types      = $this->db->fetchAll("SELECT * FROM property_types ORDER BY name");
        $regions    = $this->db->fetchAll("SELECT * FROM regions ORDER BY name");
        $owners     = $this->db->fetchAll("SELECT id, CONCAT(first_name,' ',last_name) AS name FROM users WHERE role_id IN (1,2) ORDER BY first_name");
        $managers   = $this->db->fetchAll("SELECT id, CONCAT(first_name,' ',last_name) AS name FROM users WHERE role_id IN (1,2,3) ORDER BY first_name");
        $amenities  = $this->db->fetchAll("SELECT * FROM amenities ORDER BY category, name");
        $selAmenities = array_column($this->model->getAmenities((int)$id), 'id');
        $this->adminView('property.form', compact('property','types','regions','owners','managers','amenities','selAmenities') + ['title'=>'Edit Property']);
    }

    public function update(string $id): void
    {
        $this->verifyCsrf();
        $data = [
            'owner_id'         => $this->input('owner_id') ?: null,
            'manager_id'       => $this->input('manager_id') ?: null,
            'property_type_id' => $this->input('property_type_id') ?: null,
            'name'             => Helper::sanitize($this->input('name','')),
            'slug'             => Helper::slug($this->input('name','')),
            'description'      => $this->input('description',''),
            'address'          => Helper::sanitize($this->input('address','')),
            'region_id'        => $this->input('region_id') ?: null,
            'district_id'      => $this->input('district_id') ?: null,
            'area'             => Helper::sanitize($this->input('area','')),
            'latitude'         => $this->input('latitude') ?: null,
            'longitude'        => $this->input('longitude') ?: null,
            'total_floors'     => (int)$this->input('total_floors', 1),
            'is_featured'      => $this->input('is_featured') ? 1 : 0,
            'status'           => $this->input('status','active'),
        ];
        if (!empty($_FILES['featured_image']['name'])) {
            $path = Helper::uploadFile($_FILES['featured_image'], 'properties', ALLOWED_IMAGE_TYPES);
            if ($path) $data['featured_image'] = $path;
        }
        $this->model->update((int)$id, $data);
        // Update amenities
        $this->db->delete('property_amenities', 'property_id=?', [$id]);
        foreach ($_POST['amenities'] ?? [] as $amenityId) {
            $this->db->insert('property_amenities', ['property_id' => $id, 'amenity_id' => $amenityId]);
        }
        Helper::setFlash('success', 'Property updated successfully.');
        $this->redirect(APP_URL . '/admin/properties');
    }

    public function destroy(string $id): void
    {
        $this->verifyCsrf();
        $this->model->delete((int)$id);
        Helper::setFlash('success', 'Property deleted.');
        $this->redirect(APP_URL . '/admin/properties');
    }
}
