<?php

namespace App\Http\Controllers;

use App\Models\Project;
use App\Models\ProjectDocument;
use App\Models\ProjectAuditLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ProjectDocumentController extends Controller
{
    public function listDocuments($projectId)
    {
        $project = Project::findOrFail($projectId);
        
        return response()->json([
            'documents' => $project->documents()
                ->with('uploader', 'approver')
                ->latest()
                ->get()
                ->map(fn($doc) => [
                    ...$doc->toArray(),
                    'url' => $doc->getUrl(),
                ]),
        ]);
    }

    public function getDocumentsByType($projectId, $type)
    {
        $project = Project::findOrFail($projectId);
        
        return response()->json([
            'documents' => $project->documents()
                ->where('document_type', $type)
                ->with('uploader', 'approver')
                ->latest()
                ->get()
                ->map(fn($doc) => [
                    ...$doc->toArray(),
                    'url' => $doc->getUrl(),
                ]),
        ]);
    }

    public function uploadDocument($projectId, Request $request)
    {
        $project = Project::findOrFail($projectId);

        $validated = $request->validate([
            'file' => 'required|file|max:10240',
            'name' => 'required|string',
            'document_type' => 'required|string',
            'category' => 'required|string',
            'description' => 'nullable|string',
            'phase_number' => 'nullable|integer',
            'upload_notes' => 'nullable|string',
        ]);

        $file = $request->file('file');
        $path = $file->store("projects/{$projectId}/documents", 'public');

        $document = $project->documents()->create([
            'name' => $validated['name'],
            'document_type' => $validated['document_type'],
            'category' => $validated['category'],
            'description' => $validated['description'] ?? null,
            'file_path' => $path,
            'file_name' => $file->getClientOriginalName(),
            'file_size' => $file->getSize(),
            'mime_type' => $this->resolveUploadedFileMimeType($file),
            'phase_number' => $validated['phase_number'] ?? null,
            'uploaded_by' => auth()->id(),
            'uploaded_at' => now(),
            'upload_notes' => $validated['upload_notes'] ?? null,
        ]);

        ProjectAuditLog::log(
            $project,
            'document_uploaded',
            "Document '{$document->name}' ({$validated['document_type']}) has been uploaded",
            auth()->user(),
            'document',
            $document->id
        );

        return response()->json([
            'success' => true,
            'document' => [
                ...$document->toArray(),
                'url' => $document->getUrl(),
            ],
        ], 201);
    }

    public function approveDocument($projectId, $documentId, Request $request)
    {
        $document = ProjectDocument::where('project_id', $projectId)
            ->findOrFail($documentId);

        $document->approve(auth()->user());

        ProjectAuditLog::log(
            $document->project,
            'document_approved',
            "Document '{$document->name}' has been approved",
            auth()->user(),
            'document',
            $document->id
        );

        return response()->json(['success' => true, 'document' => $document]);
    }

    public function deleteDocument($projectId, $documentId)
    {
        $document = ProjectDocument::where('project_id', $projectId)
            ->findOrFail($documentId);

        Storage::disk('public')->delete($document->file_path);
        
        $name = $document->name;
        $document->delete();

        ProjectAuditLog::log(
            $document->project,
            'document_deleted',
            "Document '{$name}' has been deleted",
            auth()->user()
        );

        return response()->json(['success' => true]);
    }

    private function resolveUploadedFileMimeType($file): string
    {
        try {
            $mimeType = $file->getMimeType();
        } catch (\Throwable) {
            $mimeType = null;
        }

        return $mimeType ?: ($file->getClientMimeType() ?: 'application/octet-stream');
    }
}
