<?php
namespace App\Controllers;

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

class TenantPortalController extends Controller
{
    private array $tenant;

    public function __construct()
    {
        parent::__construct();
        $this->requireRole(['tenant']);
        $t = $this->db->fetch("SELECT * FROM tenants WHERE user_id=?", [$_SESSION['user_id']]);
        if (!$t) {
            Helper::setFlash('warning','Tenant profile not found. Contact administrator.');
            $this->redirect(APP_URL.'/logout');
        }
        $this->tenant = $t;
    }

    public function dashboard(): void
    {
        $lease = $this->db->fetch(
            "SELECT l.*, u.unit_number, u.monthly_rent, p.name AS property_name, p.address
             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=? AND l.status='active' LIMIT 1", [$this->tenant['id']]
        );
        $balance = (float)$this->db->fetchColumn("SELECT COALESCE(SUM(balance),0) FROM invoices WHERE tenant_id=? AND status!='cancelled'", [$this->tenant['id']]);
        $recentPayments = $this->db->fetchAll("SELECT p.*, pm.name AS method_name FROM payments p LEFT JOIN payment_methods pm ON pm.id=p.payment_method_id WHERE p.tenant_id=? ORDER BY p.payment_date DESC LIMIT 5", [$this->tenant['id']]);
        $openMaint = (int)$this->db->fetchColumn("SELECT COUNT(*) FROM maintenance_requests WHERE tenant_id=? AND status NOT IN ('completed','cancelled')", [$this->tenant['id']]);
        $notifications = $this->db->fetchAll("SELECT * FROM notifications WHERE tenant_id=? ORDER BY created_at DESC LIMIT 5", [$this->tenant['id']]);
        $this->view('tenant-portal.dashboard', compact('lease','balance','recentPayments','openMaint','notifications') + ['tenant'=>$this->tenant,'title'=>'My Dashboard'], 'tenant-portal');
    }

    public function payments(): void
    {
        $invoices = $this->db->fetchAll("SELECT i.*, u.unit_number FROM invoices i JOIN units u ON u.id=i.unit_id WHERE i.tenant_id=? ORDER BY i.due_date DESC", [$this->tenant['id']]);
        $payments = $this->db->fetchAll("SELECT p.*, pm.name AS method_name FROM payments p LEFT JOIN payment_methods pm ON pm.id=p.payment_method_id WHERE p.tenant_id=? ORDER BY p.payment_date DESC", [$this->tenant['id']]);
        $methods  = $this->db->fetchAll("SELECT * FROM payment_methods WHERE is_active=1 ORDER BY sort_order");
        $this->view('tenant-portal.payments', compact('invoices','payments','methods') + ['tenant'=>$this->tenant,'title'=>'My Payments'], 'tenant-portal');
    }

    public function maintenance(): void
    {
        $requests = $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", [$this->tenant['id']]);
        $lease = $this->db->fetch("SELECT l.unit_id FROM leases l WHERE l.tenant_id=? AND l.status='active' LIMIT 1", [$this->tenant['id']]);
        $this->view('tenant-portal.maintenance', compact('requests','lease') + ['tenant'=>$this->tenant,'title'=>'Maintenance Requests'], 'tenant-portal');
    }

    public function storeRequest(): void
    {
        $this->verifyCsrf();
        $lease = $this->db->fetch("SELECT l.unit_id, l.property_id FROM leases l WHERE l.tenant_id=? AND l.status='active' LIMIT 1", [$this->tenant['id']]);
        if (!$lease) { Helper::setFlash('danger','No active lease found.'); $this->back(); return; }
        $reqNum = 'MNT-'.date('Y').'-'.str_pad((int)$this->db->fetchColumn("SELECT COUNT(*)+1 FROM maintenance_requests"), 5,'0',STR_PAD_LEFT);
        $this->db->insert('maintenance_requests', [
            'request_number' => $reqNum,
            'unit_id'        => $lease['unit_id'],
            'property_id'    => $lease['property_id'],
            'tenant_id'      => $this->tenant['id'],
            'title'          => Helper::sanitize($this->input('title','')),
            'description'    => $this->input('description',''),
            'category'       => Helper::sanitize($this->input('category','')),
            'priority'       => $this->input('priority','medium'),
            'status'         => 'open',
            'created_at'     => date('Y-m-d H:i:s'),
            'updated_at'     => date('Y-m-d H:i:s'),
        ]);
        Helper::setFlash('success','Maintenance request submitted. Reference: '.$reqNum);
        $this->redirect(APP_URL.'/tenant/maintenance');
    }

    public function profile(): void
    {
        $this->view('tenant-portal.profile', ['tenant'=>$this->tenant,'title'=>'My Profile'], 'tenant-portal');
    }

    public function updateProfile(): void
    {
        $this->verifyCsrf();
        $data = [
            'phone'     => Helper::sanitize($this->input('phone','')),
            'phone_alt' => Helper::sanitize($this->input('phone_alt','')) ?: null,
            'occupation'=> Helper::sanitize($this->input('occupation','')) ?: null,
            'address'   => $this->input('address','') ?: null,
            'emergency_contact_name'  => Helper::sanitize($this->input('emergency_contact_name','')) ?: null,
            'emergency_contact_phone' => Helper::sanitize($this->input('emergency_contact_phone','')) ?: null,
            'updated_at'=> date('Y-m-d H:i:s'),
        ];
        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=?', [$this->tenant['id']]);
        Helper::setFlash('success','Profile updated.');
        $this->redirect(APP_URL.'/tenant/profile');
    }

    public function downloadReceipt(string $paymentId): void
    {
        $payment = $this->db->fetch("SELECT * FROM payments WHERE id=? AND tenant_id=?", [$paymentId,$this->tenant['id']]);
        if (!$payment) { $this->abort(403); return; }
        $settings = array_column($this->db->fetchAll("SELECT `key`,`value` FROM settings"), 'value','key');
        header('Content-Type: text/html; charset=utf-8');
        $this->view('payment.receipt-print', compact('payment','settings') + ['tenant'=>$this->tenant,'title'=>'Receipt '.$payment['receipt_number']], '');
    }
}
