<?php
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../helpers/AuthHelper.php';

class DocumentsController
{
    public function index(): void
    {
        AuthHelper::check();
        // Busca documentos com paginação simples
        $page = max(1, (int)($_GET['page'] ?? 1));
        $limit = 12;
        $offset = ($page - 1) * $limit;

        try {
            $pdo = new PDO("mysql:host=" . DB_HOST . ";port=" . DB_PORT . ";dbname=" . DB_NAME . ";charset=utf8mb4", DB_USER, DB_PASS, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
            // Busca colaboradores para popular o select
            $empStmt = $pdo->prepare("SELECT id, full_name FROM employees ORDER BY full_name");
            $empStmt->execute();
            $employees = $empStmt->fetchAll(PDO::FETCH_ASSOC);

            // Monta query de documentos com possível filtro por colaborador
            $params = [];
            $where = '';
            if (!empty($_GET['colaborador'])) {
                $where = ' WHERE d.id_colaborador = ?';
                $params[] = (int)$_GET['colaborador'];
            }

            $sql = "SELECT d.*, u.nome as uploader, e.full_name as colaborador FROM documentos d LEFT JOIN usuarios u ON u.id = d.id_usuario LEFT JOIN employees e ON e.id = d.id_colaborador" . $where . " ORDER BY d.data_upload DESC LIMIT ? OFFSET ?";
            $stmt = $pdo->prepare($sql);
            // bind limit/offset after params
            $params[] = (int)$limit;
            $params[] = (int)$offset;
            $stmt->execute($params);
            $docs = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // total
            $tot = $pdo->query("SELECT COUNT(*) FROM documentos")->fetchColumn();
            $totalPages = (int)ceil($tot / $limit);

            $rows = $docs;
            require __DIR__ . '/../views/employees/documentos.php';
        } catch (Exception $e) {
            $errMsg = $e->getMessage();
            $rows = [];
            $employees = $employees ?? [];
            require __DIR__ . '/../views/employees/documentos.php';
        }
    }

    public function store(): void
    {
        AuthHelper::check();
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
            header('Location: ' . rtrim(BASE_URL, '/') . '/src/views/employees/documentos.php');
            exit;
        }

        try {
            $uploaderId = $_SESSION['usuario_id'] ?? $_SESSION['id'] ?? null; // tenta encontrar id do usuário
            if (!$uploaderId) throw new Exception('Usuário não identificado.');

            if (empty($_FILES['file']['name'])) throw new Exception('Nenhum arquivo enviado.');
            $file = $_FILES['file'];
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $allowed = ['pdf','jpg','jpeg','png','doc','docx','ppt','pptx'];
            if (!in_array($ext, $allowed)) throw new Exception('Extensão de arquivo não permitida.');

            // destino
            $projectRoot = dirname(__DIR__, 2);
            $uploadsDir = is_dir($projectRoot . '/public') ? $projectRoot . '/public/uploads/documentos' : $projectRoot . '/uploads/documentos';
            if (!is_dir($uploadsDir)) mkdir($uploadsDir, 0755, true);

            $safeName = bin2hex(random_bytes(8)) . '.' . $ext;
            $dest = $uploadsDir . DIRECTORY_SEPARATOR . $safeName;
            if (!move_uploaded_file($file['tmp_name'], $dest)) throw new Exception('Falha ao mover o arquivo.');

            $relPath = 'uploads/documentos/' . $safeName;
            $pdo = new PDO("mysql:host=" . DB_HOST . ";port=" . DB_PORT . ";dbname=" . DB_NAME . ";charset=utf8mb4", DB_USER, DB_PASS, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
            // Verifica se existe a coluna id_colaborador na tabela documentos
            $hasCol = false;
            $colChk = $pdo->query("SHOW COLUMNS FROM documentos LIKE 'id_colaborador'")->fetch();
            if ($colChk) $hasCol = true;

            $titulo = $_POST['titulo'] ?? ($file['name'] ?? 'Documento');
            $descricao = $_POST['descricao'] ?? null;
            $categoria = $_POST['categoria'] ?? 'Diversos';
            $colaboradorId = !empty($_POST['colaborador_id']) ? (int)$_POST['colaborador_id'] : null;

            if ($hasCol) {
                $stmt = $pdo->prepare("INSERT INTO documentos (id_usuario, id_colaborador, titulo, descricao, nome_arquivo, caminho_arquivo, tipo_arquivo, tamanho_arquivo, categoria) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([(int)$uploaderId, $colaboradorId, $titulo, $descricao, $safeName, $relPath, $file['type'], (int)$file['size'], $categoria]);
            } else {
                $stmt = $pdo->prepare("INSERT INTO documentos (id_usuario, titulo, descricao, nome_arquivo, caminho_arquivo, tipo_arquivo, tamanho_arquivo, categoria) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([(int)$uploaderId, $titulo, $descricao, $safeName, $relPath, $file['type'], (int)$file['size'], $categoria]);
            }

            $_SESSION['success'] = 'Documento enviado com sucesso.';
            header('Location: ' . rtrim(BASE_URL, '/') . '/src/views/employees/documentos.php');
            exit;
        } catch (Exception $e) {
            $_SESSION['error'] = $e->getMessage();
            header('Location: ' . rtrim(BASE_URL, '/') . '/src/views/employees/documentos.php');
            exit;
        }
    }

    public function download(int $id): void
    {
        AuthHelper::check();
        try {
            $pdo = new PDO("mysql:host=" . DB_HOST . ";port=" . DB_PORT . ";dbname=" . DB_NAME . ";charset=utf8mb4", DB_USER, DB_PASS, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
            $stmt = $pdo->prepare("SELECT * FROM documentos WHERE id = ? LIMIT 1");
            $stmt->execute([(int)$id]);
            $doc = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$doc) throw new Exception('Documento não encontrado.');

            $projectRoot = dirname(__DIR__, 2);
            $path1 = $projectRoot . '/' . ltrim($doc['caminho_arquivo'], '/\\');
            $path2 = $projectRoot . '/public/' . ltrim($doc['caminho_arquivo'], '/\\');
            $filePath = is_file($path1) ? $path1 : (is_file($path2) ? $path2 : null);
            if (!$filePath) throw new Exception('Arquivo não encontrado no servidor.');

            header('Content-Description: File Transfer');
            header('Content-Type: ' . ($doc['tipo_arquivo'] ?? 'application/octet-stream'));
            header('Content-Disposition: attachment; filename="' . basename($doc['nome_arquivo']) . '"');
            header('Content-Length: ' . filesize($filePath));
            readfile($filePath);
            exit;
        } catch (Exception $e) {
            $_SESSION['error'] = $e->getMessage();
            header('Location: ' . rtrim(BASE_URL, '/') . '/src/views/employees/documentos.php');
            exit;
        }
    }

    public function delete(int $id): void
    {
        AuthHelper::check();
        try {
            $pdo = new PDO("mysql:host=" . DB_HOST . ";port=" . DB_PORT . ";dbname=" . DB_NAME . ";charset=utf8mb4", DB_USER, DB_PASS, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
            $stmt = $pdo->prepare("SELECT * FROM documentos WHERE id = ? LIMIT 1");
            $stmt->execute([(int)$id]);
            $doc = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$doc) throw new Exception('Documento não encontrado.');

            $projectRoot = dirname(__DIR__, 2);
            $path1 = $projectRoot . '/' . ltrim($doc['caminho_arquivo'], '/\\');
            $path2 = $projectRoot . '/public/' . ltrim($doc['caminho_arquivo'], '/\\');
            if (is_file($path1)) @unlink($path1);
            if (is_file($path2)) @unlink($path2);

            $del = $pdo->prepare("DELETE FROM documentos WHERE id = ?");
            $del->execute([(int)$id]);

            $_SESSION['success'] = 'Documento excluído.';
            header('Location: ' . rtrim(BASE_URL, '/') . '/src/views/employees/documentos.php');
            exit;
        } catch (Exception $e) {
            $_SESSION['error'] = $e->getMessage();
            header('Location: ' . rtrim(BASE_URL, '/') . '/src/views/employees/documentos.php');
            exit;
        }
    }
}
