<?php
namespace App\Controllers\Api;

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

class TenantApiController extends Controller
{
    private function authTenant(): array
    {
        $token   = $this->getBearerToken();
        $record  = $token ? $this->db->fetch("SELECT * FROM api_tokens WHERE token=? AND expires_at > NOW()", [$token]) : null;
        if (!$record) { $this->json(['success' => false, 'message' => 'Unauthorized.'], 401); exit; }
        $user   = $this->db->fetch("SELECT * FROM users WHERE id=?", [$record['user_id']]);
        $tenant = $this->db->fetch("SELECT * FROM tenants WHERE user_id=?", [$user['id']]);
        if (!$tenant) { $this->json(['success' => false, 'message' => 'Tenant profile not found.'], 403); exit; }
        return $tenant;
    }

    private function getBearerToken(): ?string
    {
        $h = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
        if (preg_match('/Bearer\s+(.+)/i', $h, $m)) return $m[1];
        return null;
    }

    public function dashboard(): void
    {
        $tenant = $this->authTenant();
        $lease  = $this->db->fetch("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=? AND l.status='active' LIMIT 1", [$tenant['id']]);
        $balance = (float)$this->db->fetchColumn("SELECT COALESCE(SUM(balance),0) FROM invoices WHERE tenant_id=? AND status!='cancelled'", [$tenant['id']]);
        $this->json(['success' => true, 'data' => ['tenant' => $tenant, 'lease' => $lease, 'balance' => $balance]]);
    }

    public function invoices(): void
    {
        $tenant   = $this->authTenant();
        $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", [$tenant['id']]);
        $this->json(['success' => true, 'data' => $invoices]);
    }

    public function payments(): void
    {
        $tenant   = $this->authTenant();
        $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", [$tenant['id']]);
        $this->json(['success' => true, 'data' => $payments]);
    }

    public function maintenance(): void
    {
        $tenant   = $this->authTenant();
        $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", [$tenant['id']]);
        $this->json(['success' => true, 'data' => $requests]);
    }

    public function storeRequest(): void
    {
        $tenant = $this->authTenant();
        $input  = json_decode(file_get_contents('php://input'), true) ?? $_POST;
        $lease  = $this->db->fetch("SELECT unit_id, property_id FROM leases WHERE tenant_id=? AND status='active' LIMIT 1", [$tenant['id']]);
        if (!$lease) { $this->json(['success' => false, 'message' => 'No active lease.'], 400); 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'      => $tenant['id'],
            'title'          => htmlspecialchars($input['title'] ?? ''),
            'description'    => $input['description'] ?? '',
            'category'       => htmlspecialchars($input['category'] ?? 'General'),
            'priority'       => $input['priority'] ?? 'medium',
            'status'         => 'open',
            'created_at'     => date('Y-m-d H:i:s'),
            'updated_at'     => date('Y-m-d H:i:s'),
        ]);
        $this->json(['success' => true, 'message' => 'Request submitted.', 'request_number' => $reqNum]);
    }
}
