<?php
class OwnerController {
    private $db;

    public function __construct() { $this->db = Database::getInstance(); }

    public function index() {
        $search = $_GET['search'] ?? '';
        $page = max(1, intval($_GET['pg'] ?? 1));
        $perPage = ITEMS_PER_PAGE;

        $where = "WHERE o.deleted_at IS NULL AND o.company_id = ?";
        $params = [Auth::user()['company_id']];

        if ($search) {
            $where .= " AND (o.name LIKE ? OR o.email LIKE ? OR o.phone LIKE ?)";
            $s = "%$search%";
            $params = array_merge($params, [$s, $s, $s]);
        }

        $total = $this->db->fetchColumn("SELECT COUNT(*) FROM owners o $where", $params);
        $offset = ($page - 1) * $perPage;

        $owners = $this->db->fetchAll("SELECT o.*, (SELECT COUNT(*) FROM properties p WHERE p.owner_id = o.id AND p.deleted_at IS NULL) as property_count FROM owners o $where ORDER BY o.name ASC LIMIT $perPage OFFSET $offset", $params);

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

    public function create() {
        $owner = null;
        require 'app/views/owners/form.php';
    }

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

        $this->db->insert('owners', [
            'company_id' => Auth::user()['company_id'], 'name' => $_POST['name'], 'email' => $_POST['email'],
            'phone' => $_POST['phone'] ?? null, 'address' => $_POST['address'] ?? null,
            'city' => $_POST['city'] ?? null, 'state' => $_POST['state'] ?? null,
            'zip' => $_POST['zip'] ?? null, 'notes' => $_POST['notes'] ?? null,
        ]);
        flash('success', 'Owner created successfully.');
        redirect('?page=owners');
    }

    public function show($id) {
        $owner = $this->db->fetch("SELECT * FROM owners WHERE id = ? AND company_id = ? AND deleted_at IS NULL", [$id, Auth::user()['company_id']]);
        if (!$owner) { flash('error', 'Owner not found.'); redirect('?page=owners'); }

        $properties = $this->db->fetchAll("SELECT * FROM properties WHERE owner_id = ? AND deleted_at IS NULL", [$id]);

        // Financial summary
        $income = $this->db->fetchColumn("SELECT COALESCE(SUM(p.amount),0) FROM payments p JOIN leases l ON p.lease_id = l.id JOIN units u ON l.unit_id = u.id JOIN properties pr ON u.property_id = pr.id WHERE pr.owner_id = ? AND p.status = 'completed' AND p.deleted_at IS NULL", [$id]);
        $expenses = $this->db->fetchColumn("SELECT COALESCE(SUM(amount),0) FROM expenses WHERE property_id IN (SELECT id FROM properties WHERE owner_id = ? AND deleted_at IS NULL) AND deleted_at IS NULL", [$id]);

        require 'app/views/owners/show.php';
    }

    public function edit($id) {
        $owner = $this->db->fetch("SELECT * FROM owners WHERE id = ? AND company_id = ? AND deleted_at IS NULL", [$id, Auth::user()['company_id']]);
        if (!$owner) { flash('error', 'Owner not found.'); redirect('?page=owners'); }
        require 'app/views/owners/form.php';
    }

    public function update($id) {
        CSRF::verify();
        $v = new Validator($_POST);
        $v->required('name')->required('email')->email('email');
        if ($v->fails()) { flash('error', implode('<br>', $v->errors())); redirect("?page=owners&action=edit&id=$id"); }

        $this->db->update('owners', [
            'name' => $_POST['name'], 'email' => $_POST['email'],
            'phone' => $_POST['phone'] ?? null, 'address' => $_POST['address'] ?? null,
            'city' => $_POST['city'] ?? null, 'state' => $_POST['state'] ?? null,
            'zip' => $_POST['zip'] ?? null, 'notes' => $_POST['notes'] ?? null,
        ], 'id = ? AND company_id = ?', [$id, Auth::user()['company_id']]);
        flash('success', 'Owner updated successfully.');
        redirect('?page=owners');
    }

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