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

    public function index() {
        $search = $_GET['search'] ?? ''; $type = $_GET['type'] ?? '';
        $page = max(1, intval($_GET['pg'] ?? 1)); $perPage = ITEMS_PER_PAGE; $cid = Auth::user()['company_id'];
        $where = "WHERE c.deleted_at IS NULL AND c.company_id = ?"; $params = [$cid];
        if ($search) { $where .= " AND (c.subject LIKE ? OR c.body LIKE ? OR t.first_name LIKE ? OR t.last_name LIKE ?)"; $s = "%$search%"; $params = array_merge($params, [$s,$s,$s,$s]); }
        if ($type) { $where .= " AND c.type = ?"; $params[] = $type; }
        $total = $this->db->fetchColumn("SELECT COUNT(*) FROM communications c LEFT JOIN tenants t ON c.recipient_id=t.id AND c.recipient_type='tenant' $where", $params);
        $offset = ($page - 1) * $perPage;
        $messages = $this->db->fetchAll("SELECT c.*, CASE WHEN c.recipient_type='tenant' THEN (SELECT CONCAT(first_name,' ',last_name) FROM tenants WHERE id=c.recipient_id) WHEN c.recipient_type='owner' THEN (SELECT CONCAT(first_name,' ',last_name) FROM owners WHERE id=c.recipient_id) WHEN c.recipient_type='vendor' THEN (SELECT company_name FROM vendors WHERE id=c.recipient_id) ELSE 'Unknown' END as recipient_name FROM communications c LEFT JOIN tenants t ON c.recipient_id=t.id AND c.recipient_type='tenant' $where ORDER BY c.created_at DESC LIMIT $perPage OFFSET $offset", $params);
        $pagination = paginationHtml($total, $page, $perPage, '?page=communications');
        require 'app/views/communications/index.php';
    }

    public function create() {
        $cid = Auth::user()['company_id'];
        $tenants = $this->db->fetchAll("SELECT id, first_name, last_name, email FROM tenants WHERE company_id=? AND deleted_at IS NULL ORDER BY first_name", [$cid]);
        $owners = $this->db->fetchAll("SELECT id, first_name, last_name, email FROM owners WHERE company_id=? AND deleted_at IS NULL ORDER BY first_name", [$cid]);
        $vendors = $this->db->fetchAll("SELECT id, company_name, email FROM vendors WHERE company_id=? AND deleted_at IS NULL ORDER BY company_name", [$cid]);
        require 'app/views/communications/form.php';
    }

    public function store() {
        CSRF::verify();
        $v = new Validator($_POST); $v->required('subject')->required('body')->required('recipient_type')->required('recipient_id');
        if ($v->fails()) { flash('error', implode('<br>', $v->errors())); redirect('?page=communications&action=create'); }
        $this->db->insert('communications', [
            'company_id' => Auth::user()['company_id'], 'type' => $_POST['type'] ?? 'email',
            'recipient_type' => $_POST['recipient_type'], 'recipient_id' => $_POST['recipient_id'],
            'subject' => $_POST['subject'], 'body' => $_POST['body'],
            'status' => 'sent', 'sent_by' => Auth::user()['id'], 'sent_at' => date('Y-m-d H:i:s'),
        ]);
        auditLog('communication_sent', 'communications', $this->db->lastInsertId());
        flash('success', 'Message sent.'); redirect('?page=communications');
    }

    public function show($id) {
        $msg = $this->db->fetch("SELECT c.*, u.first_name as sender_first, u.last_name as sender_last FROM communications c LEFT JOIN users u ON c.sent_by=u.id WHERE c.id=? AND c.company_id=? AND c.deleted_at IS NULL", [$id, Auth::user()['company_id']]);
        if (!$msg) { flash('error', 'Message not found.'); redirect('?page=communications'); }
        require 'app/views/communications/show.php';
    }

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