<?php
namespace App\Controllers;

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

class TenantController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->requireRole(['super_admin','property_owner','property_manager','receptionist']);
    }

    public function index(): void
    {
        $page = max(1,(int)($_GET['page']??1));
        $search = Helper::sanitize($_GET['search'] ?? '');
        $where = $search ? "status != 'blacklisted' AND (first_name LIKE ? OR last_name LIKE ? OR phone LIKE ? OR tenant_code LIKE ?)" : "1=1";
        $params = $search ? ["%$search%","%$search%","%$search%","%$search%"] : [];
        $total = $this->db->fetchColumn("SELECT COUNT(*) FROM tenants WHERE $where", $params);
        $pagination = $this->paginate((int)$total);
        $tenants = $this->db->fetchAll("SELECT t.*, u.email AS user_email FROM tenants t LEFT JOIN users u ON u.id=t.user_id WHERE $where ORDER BY t.created_at DESC LIMIT ? OFFSET ?", array_merge($params, [$pagination['perPage'],$pagination['offset']]));
        $this->adminView('tenant.index', compact('tenants','pagination','search') + ['title'=>'Tenants','breadcrumb'=>[['label'=>'Tenants']]]);
    }

    public function create(): void
    {
        $regions = $this->db->fetchAll("SELECT * FROM regions ORDER BY name");
        $this->adminView('tenant.form', compact('regions') + ['title'=>'Add Tenant','tenant'=>null]);
    }

    public function store(): void
    {
        $this->verifyCsrf();
        $data = [
            'tenant_code'     => Helper::generateCode('TNT', 6),
            'first_name'      => Helper::sanitize($this->input('first_name','')),
            'last_name'       => Helper::sanitize($this->input('last_name','')),
            'email'           => filter_var($this->input('email',''), FILTER_SANITIZE_EMAIL) ?: null,
            'phone'           => Helper::sanitize($this->input('phone','')),
            'phone_alt'       => Helper::sanitize($this->input('phone_alt','')) ?: null,
            'date_of_birth'   => $this->input('date_of_birth') ?: null,
            'gender'          => $this->input('gender') ?: null,
            'nationality'     => Helper::sanitize($this->input('nationality','Tanzanian')),
            'national_id'     => Helper::sanitize($this->input('national_id','')) ?: null,
            'passport_number' => Helper::sanitize($this->input('passport_number','')) ?: null,
            'occupation'      => Helper::sanitize($this->input('occupation','')) ?: null,
            'employer'        => Helper::sanitize($this->input('employer','')) ?: null,
            'monthly_income'  => $this->input('monthly_income') ?: null,
            'emergency_contact_name'     => Helper::sanitize($this->input('emergency_contact_name','')) ?: null,
            'emergency_contact_phone'    => Helper::sanitize($this->input('emergency_contact_phone','')) ?: null,
            'emergency_contact_relation' => Helper::sanitize($this->input('emergency_contact_relation','')) ?: null,
            'address'         => $this->input('address','') ?: null,
            'region_id'       => $this->input('region_id') ?: null,
            'notes'           => $this->input('notes','') ?: null,
            'status'          => 'active',
        ];

        // Upload photo
        if (!empty($_FILES['photo']['name'])) {
            $path = Helper::uploadFile($_FILES['photo'], 'avatars', ALLOWED_IMAGE_TYPES);
            if ($path) $data['photo'] = $path;
        }
        // Upload ID document
        if (!empty($_FILES['id_document']['name'])) {
            $path = Helper::uploadFile($_FILES['id_document'], 'documents', ALLOWED_DOC_TYPES);
            if ($path) $data['id_document'] = $path;
        }

        // Create user account if email provided
        if ($data['email']) {
            $existing = $this->db->fetch("SELECT id FROM users WHERE email=?", [$data['email']]);
            if (!$existing) {
                $password = Helper::generateCode('Zb', 6) . '@';
                $userId = $this->db->insert('users', [
                    'role_id'   => 6,
                    'first_name'=> $data['first_name'],
                    'last_name' => $data['last_name'],
                    'email'     => $data['email'],
                    'phone'     => $data['phone'],
                    'password'  => password_hash($password, PASSWORD_BCRYPT, ['cost'=>12]),
                    'status'    => 'active',
                    'created_at'=> date('Y-m-d H:i:s'),
                    'updated_at'=> date('Y-m-d H:i:s'),
                ]);
                $data['user_id'] = $userId;
            } else {
                $data['user_id'] = $existing['id'];
            }
        }

        try {
            $id = $this->db->insert('tenants', $data);
            Helper::setFlash('success', 'Tenant added successfully. Code: ' . $data['tenant_code']);
            $this->redirect(APP_URL . '/admin/tenants/' . $id);
        } catch (\Exception $e) {
            Helper::setFlash('danger', 'Error creating tenant: ' . $e->getMessage());
            $this->back();
        }
    }

    public function show(string $id): void
    {
        $tenant = $this->db->fetch("SELECT t.*, r.name AS region_name FROM tenants t LEFT JOIN regions r ON r.id=t.region_id WHERE t.id=?", [$id]);
        if (!$tenant) { $this->abort(404); return; }
        $leases = $this->db->fetchAll("SELECT l.*, u.unit_number, p.name AS property_name FROM leases l JOIN units u ON u.id=l.unit_id JOIN properties p ON p.id=l.property_id WHERE l.tenant_id=? ORDER BY l.created_at DESC", [$id]);
        $payments = $this->db->fetchAll("SELECT pay.*, pm.name AS method_name FROM payments pay LEFT JOIN payment_methods pm ON pm.id=pay.payment_method_id WHERE pay.tenant_id=? ORDER BY pay.payment_date DESC LIMIT 20", [$id]);
        $maintenance = $this->db->fetchAll("SELECT mr.*, u.unit_number FROM maintenance_requests mr JOIN units u ON u.id=mr.unit_id WHERE mr.tenant_id=? ORDER BY mr.created_at DESC LIMIT 10", [$id]);
        $stats = [
            'total_paid'    => (float)$this->db->fetchColumn("SELECT COALESCE(SUM(amount),0) FROM payments WHERE tenant_id=? AND status='completed'", [$id]),
            'balance'       => (float)$this->db->fetchColumn("SELECT COALESCE(SUM(balance),0) FROM invoices WHERE tenant_id=? AND status!='cancelled'", [$id]),
            'active_leases' => (int)$this->db->fetchColumn("SELECT COUNT(*) FROM leases WHERE tenant_id=? AND status='active'", [$id]),
        ];
        $this->adminView('tenant.show', compact('tenant','leases','payments','maintenance','stats') + ['title' => $tenant['first_name'].' '.$tenant['last_name']]);
    }

    public function edit(string $id): void
    {
        $tenant  = $this->db->fetch("SELECT * FROM tenants WHERE id=?", [$id]);
        if (!$tenant) { $this->abort(404); return; }
        $regions = $this->db->fetchAll("SELECT * FROM regions ORDER BY name");
        $this->adminView('tenant.form', compact('tenant','regions') + ['title'=>'Edit Tenant']);
    }

    public function update(string $id): void
    {
        $this->verifyCsrf();
        $data = [
            'first_name'   => Helper::sanitize($this->input('first_name','')),
            'last_name'    => Helper::sanitize($this->input('last_name','')),
            'phone'        => Helper::sanitize($this->input('phone','')),
            'phone_alt'    => Helper::sanitize($this->input('phone_alt','')) ?: null,
            'occupation'   => Helper::sanitize($this->input('occupation','')) ?: null,
            'employer'     => Helper::sanitize($this->input('employer','')) ?: null,
            'monthly_income' => $this->input('monthly_income') ?: null,
            'emergency_contact_name'  => Helper::sanitize($this->input('emergency_contact_name','')) ?: null,
            'emergency_contact_phone' => Helper::sanitize($this->input('emergency_contact_phone','')) ?: null,
            'address'      => $this->input('address','') ?: null,
            'region_id'    => $this->input('region_id') ?: null,
            'notes'        => $this->input('notes','') ?: null,
            'status'       => $this->input('status','active'),
        ];
        if (!empty($_FILES['photo']['name'])) {
            $path = Helper::uploadFile($_FILES['photo'], 'avatars', ALLOWED_IMAGE_TYPES);
            if ($path) $data['photo'] = $path;
        }
        $this->db->update('tenants', $data, 'id=?', [$id]);
        Helper::setFlash('success', 'Tenant updated successfully.');
        $this->redirect(APP_URL . '/admin/tenants/' . $id);
    }

    public function destroy(string $id): void
    {
        $this->verifyCsrf();
        $this->db->update('tenants', ['status'=>'inactive'], 'id=?', [$id]);
        Helper::setFlash('success', 'Tenant deactivated.');
        $this->redirect(APP_URL . '/admin/tenants');
    }
}
