<?php
class PaymentController {
    private $db;
    public function __construct() { $this->db = Database::getInstance(); }

    public function index() {
        $search = $_GET['search'] ?? ''; $status = $_GET['status'] ?? ''; $method = $_GET['method'] ?? '';
        $page = max(1, intval($_GET['pg'] ?? 1)); $perPage = ITEMS_PER_PAGE; $cid = Auth::user()['company_id'];

        $where = "WHERE p.deleted_at IS NULL AND p.company_id = ?"; $params = [$cid];
        if ($search) { $where .= " AND (t.first_name LIKE ? OR t.last_name LIKE ? OR p.reference_number LIKE ?)"; $s = "%$search%"; $params = array_merge($params, [$s,$s,$s]); }
        if ($status) { $where .= " AND p.status = ?"; $params[] = $status; }
        if ($method) { $where .= " AND p.payment_method = ?"; $params[] = $method; }

        $total = $this->db->fetchColumn("SELECT COUNT(*) FROM payments p LEFT JOIN tenants t ON p.tenant_id=t.id $where", $params);
        $offset = ($page - 1) * $perPage;
        $payments = $this->db->fetchAll("SELECT p.*, t.first_name, t.last_name, pr.name as property_name FROM payments p LEFT JOIN tenants t ON p.tenant_id=t.id LEFT JOIN leases l ON p.lease_id=l.id LEFT JOIN properties pr ON l.property_id=pr.id $where ORDER BY p.payment_date DESC LIMIT $perPage OFFSET $offset", $params);

        // Summary stats
        $totalCollected = $this->db->fetchColumn("SELECT COALESCE(SUM(amount),0) FROM payments WHERE company_id=? AND status='completed' AND deleted_at IS NULL AND MONTH(payment_date)=MONTH(NOW()) AND YEAR(payment_date)=YEAR(NOW())", [$cid]);
        $totalPending = $this->db->fetchColumn("SELECT COALESCE(SUM(amount),0) FROM payments WHERE company_id=? AND status='pending' AND deleted_at IS NULL", [$cid]);

        $pagination = paginationHtml($total, $page, $perPage, '?page=payments');
        require 'app/views/payments/index.php';
    }

    public function create() {
        $payment = null; $cid = Auth::user()['company_id'];
        $tenants = $this->db->fetchAll("SELECT id, first_name, last_name FROM tenants WHERE company_id=? AND deleted_at IS NULL ORDER BY first_name", [$cid]);
        $leases = $this->db->fetchAll("SELECT l.id, l.rent_amount, t.first_name, t.last_name, u.unit_number FROM leases l JOIN tenants t ON l.tenant_id=t.id LEFT JOIN units u ON l.unit_id=u.id WHERE l.company_id=? AND l.status='active' AND l.deleted_at IS NULL", [$cid]);
        require 'app/views/payments/form.php';
    }

    public function store() {
        CSRF::verify();
        $v = new Validator($_POST);
        $v->required('tenant_id')->required('amount')->numeric('amount')->required('payment_date');
        if ($v->fails()) { flash('error', implode('<br>', $v->errors())); redirect('?page=payments&action=create'); }

        $this->db->insert('payments', [
            'company_id' => Auth::user()['company_id'], 'tenant_id' => $_POST['tenant_id'],
            'lease_id' => $_POST['lease_id'] ?: null, 'amount' => $_POST['amount'],
            'payment_date' => $_POST['payment_date'], 'payment_method' => $_POST['payment_method'] ?? 'manual',
            'status' => $_POST['status'] ?? 'completed', 'reference_number' => $_POST['reference_number'] ?? null,
            'notes' => $_POST['notes'] ?? null,
        ]);
        auditLog('payment_created', 'payments', $this->db->lastInsertId());
        flash('success', 'Payment recorded.');
        redirect('?page=payments');
    }

    public function show($id) {
        $cid = Auth::user()['company_id'];
        $payment = $this->db->fetch("SELECT p.*, t.first_name, t.last_name, t.email as tenant_email, l.rent_amount, pr.name as property_name, u.unit_number FROM payments p LEFT JOIN tenants t ON p.tenant_id=t.id LEFT JOIN leases l ON p.lease_id=l.id LEFT JOIN properties pr ON l.property_id=pr.id LEFT JOIN units u ON l.unit_id=u.id WHERE p.id=? AND p.company_id=? AND p.deleted_at IS NULL", [$id, $cid]);
        if (!$payment) { flash('error', 'Payment not found.'); redirect('?page=payments'); }
        require 'app/views/payments/show.php';
    }

    public function edit($id) {
        $cid = Auth::user()['company_id'];
        $payment = $this->db->fetch("SELECT * FROM payments WHERE id=? AND company_id=? AND deleted_at IS NULL", [$id, $cid]);
        if (!$payment) { flash('error', 'Payment not found.'); redirect('?page=payments'); }
        $tenants = $this->db->fetchAll("SELECT id, first_name, last_name FROM tenants WHERE company_id=? AND deleted_at IS NULL ORDER BY first_name", [$cid]);
        $leases = $this->db->fetchAll("SELECT l.id, l.rent_amount, t.first_name, t.last_name, u.unit_number FROM leases l JOIN tenants t ON l.tenant_id=t.id LEFT JOIN units u ON l.unit_id=u.id WHERE l.company_id=? AND l.deleted_at IS NULL", [$cid]);
        require 'app/views/payments/form.php';
    }

    public function update($id) {
        CSRF::verify();
        $this->db->update('payments', [
            'tenant_id' => $_POST['tenant_id'], 'lease_id' => $_POST['lease_id'] ?: null,
            'amount' => $_POST['amount'], 'payment_date' => $_POST['payment_date'],
            'payment_method' => $_POST['payment_method'] ?? 'manual', 'status' => $_POST['status'] ?? 'completed',
            'reference_number' => $_POST['reference_number'] ?? null, 'notes' => $_POST['notes'] ?? null,
        ], 'id = ? AND company_id = ?', [$id, Auth::user()['company_id']]);
        flash('success', 'Payment updated.');
        redirect('?page=payments');
    }

    public function delete($id) {
        CSRF::verify();
        $this->db->softDelete('payments', 'id = ? AND company_id = ?', [$id, Auth::user()['company_id']]);
        flash('success', 'Payment deleted.');
        redirect('?page=payments');
    }
}
