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

    public function index() {
        $search = $_GET['search'] ?? ''; $category = $_GET['category'] ?? '';
        $page = max(1, intval($_GET['pg'] ?? 1)); $perPage = ITEMS_PER_PAGE; $cid = Auth::user()['company_id'];
        $where = "WHERE d.deleted_at IS NULL AND d.company_id = ?"; $params = [$cid];
        if ($search) { $where .= " AND (d.title LIKE ? OR d.filename LIKE ?)"; $s = "%$search%"; $params = array_merge($params, [$s,$s]); }
        if ($category) { $where .= " AND d.category = ?"; $params[] = $category; }
        $total = $this->db->fetchColumn("SELECT COUNT(*) FROM documents d $where", $params);
        $offset = ($page - 1) * $perPage;
        $documents = $this->db->fetchAll("SELECT d.*, u.first_name as uploader_first, u.last_name as uploader_last FROM documents d LEFT JOIN users u ON d.uploaded_by=u.id $where ORDER BY d.created_at DESC LIMIT $perPage OFFSET $offset", $params);
        $pagination = paginationHtml($total, $page, $perPage, '?page=documents');
        require 'app/views/documents/index.php';
    }

    public function create() {
        $cid = Auth::user()['company_id'];
        $properties = $this->db->fetchAll("SELECT id, name FROM properties WHERE company_id=? AND deleted_at IS NULL ORDER BY name", [$cid]);
        $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]);
        require 'app/views/documents/form.php';
    }

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

        $filePath = null; $filename = null; $fileSize = null; $mimeType = null;
        if (!empty($_FILES['file']['name'])) {
            $result = uploadFile($_FILES['file'], 'documents');
            if ($result['success']) { $filePath = $result['path']; $filename = $_FILES['file']['name']; $fileSize = $_FILES['file']['size']; $mimeType = $_FILES['file']['type']; }
            else { flash('error', $result['error']); redirect('?page=documents&action=create'); }
        }

        $this->db->insert('documents', [
            'company_id' => Auth::user()['company_id'], 'title' => $_POST['title'],
            'filename' => $filename, 'file_path' => $filePath, 'file_size' => $fileSize, 'mime_type' => $mimeType,
            'category' => $_POST['category'] ?? null, 'description' => $_POST['description'] ?? null,
            'documentable_type' => $_POST['documentable_type'] ?? null, 'documentable_id' => $_POST['documentable_id'] ?: null,
            'uploaded_by' => Auth::user()['id'], 'expiry_date' => $_POST['expiry_date'] ?: null,
        ]);
        flash('success', 'Document uploaded.'); redirect('?page=documents');
    }

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

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

    public function download($id) {
        $doc = $this->db->fetch("SELECT * FROM documents WHERE id=? AND company_id=? AND deleted_at IS NULL", [$id, Auth::user()['company_id']]);
        if (!$doc || !$doc['file_path'] || !file_exists($doc['file_path'])) { flash('error', 'File not found.'); redirect('?page=documents'); }
        header('Content-Type: ' . ($doc['mime_type'] ?? 'application/octet-stream'));
        header('Content-Disposition: attachment; filename="' . basename($doc['filename'] ?? 'download') . '"');
        header('Content-Length: ' . filesize($doc['file_path']));
        readfile($doc['file_path']); exit;
    }
}
