<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Helpers\Auth;
use App\Helpers\Url;
use App\Models\Document;
use App\Models\DocumentCategory;
use App\Models\AuditLog;

class DocumentController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        Auth::requireLogin();
    }

    public function index()
    {
        $categoryModel = new DocumentCategory();
        $categories = $categoryModel->getWithCounts();
        $this->view('documents/index', ['categories' => $categories]);
    }

    public function category($params)
    {
        $catId = $params['id'] ?? null;
        $categoryModel = new DocumentCategory();
        $category = $categoryModel->find($catId);

        if (!$category) {
            $_SESSION['error'] = 'Category not found';
            $this->redirect('/documents');
        }

        $documentModel = new Document();
        $documents = $documentModel->getByCategory($catId);

        $this->view('documents/category', ['category' => $category, 'documents' => $documents]);
    }

    public function upload()
    {
        $categoryModel = new DocumentCategory();
        $categories = $categoryModel->all();
        $this->view('documents/upload', ['categories' => $categories]);
    }

    public function store()
    {
        $title = $_POST['title'] ?? '';
        $description = $_POST['description'] ?? '';
        $categoryId = $_POST['category_id'] ?? null;
        $isPublic = isset($_POST['is_public']) ? 1 : 0;

        if (empty($title) || !isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
            $_SESSION['error'] = 'Title and file are required';
            $this->redirect('/documents/upload');
        }

        $file = $_FILES['file'];
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $filename = 'doc_' . time() . '_' . Auth::id() . '.' . $ext;
        $uploadDir = $_SERVER['DOCUMENT_ROOT'] . Url::getBaseUrl() . '/uploads/documents/';

        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $dest = $uploadDir . $filename;
        move_uploaded_file($file['tmp_name'], $dest);

        $documentModel = new Document();
        $documentModel->create([
            'category_id' => $categoryId,
            'user_id' => Auth::id(),
            'title' => $title,
            'description' => $description,
            'file_path' => '/uploads/documents/' . $filename,
            'file_type' => $file['type'],
            'file_size' => $file['size'],
            'is_public' => $isPublic,
        ]);

        $audit = new AuditLog();
        $audit->log(Auth::id(), 'document.upload', 'documents', $documentModel->db->lastInsertId(), "Uploaded document: {$title}");

        $_SESSION['success'] = 'Document uploaded successfully';
        $this->redirect('/documents');
    }

    public function download($params)
    {
        $id = $params['id'] ?? null;
        $documentModel = new Document();
        $doc = $documentModel->find($id);

        if (!$doc) {
            $_SESSION['error'] = 'Document not found';
            $this->redirect('/documents');
        }

        $filePath = $_SERVER['DOCUMENT_ROOT'] . Url::getBaseUrl() . '/' . ltrim($doc->file_path, '/');
        if (file_exists($filePath)) {
            $documentModel->incrementDownload($id);
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
            header('Content-Length: ' . filesize($filePath));
            readfile($filePath);
            exit;
        }

        $_SESSION['error'] = 'File not found';
        $this->redirect('/documents');
    }

    public function delete($params)
    {
        $id = $params['id'] ?? null;
        $documentModel = new Document();
        $doc = $documentModel->find($id);

        if ($doc) {
            $filePath = $_SERVER['DOCUMENT_ROOT'] . Url::getBaseUrl() . '/' . ltrim($doc->file_path, '/');
            if (file_exists($filePath)) unlink($filePath);

            $audit = new AuditLog();
            $audit->log(Auth::id(), 'document.delete', 'documents', $id, "Deleted document: {$doc->title}");
            $documentModel->delete($id);
            $_SESSION['success'] = 'Document deleted';
        }
        $this->redirect('/documents');
    }
}
