<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Document;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class DocumentController extends Controller
{
    /**
     * Get documents for a specific entity (requisition, order, quotation, etc.)
     */
    public function index(Request $request)
    {
        $request->validate([
            'documentable_type' => 'required|string',
            'documentable_id' => 'required|integer',
            'document_type' => 'nullable|string|max:255',
        ]);

        // Normalize documentable_type (convert double backslashes to single)
        $documentableType = str_replace('\\\\', '\\', $request->documentable_type);

        $query = Document::where('documentable_type', $documentableType)
            ->where('documentable_id', $request->documentable_id);

        if ($request->filled('document_type')) {
            $query->where('document_type', $request->document_type);
        }

        $documents = $query->orderBy('created_at', 'desc')->get();

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

    /**
     * Store a newly uploaded document.
     */
    public function store(Request $request)
    {
        $request->validate([
            'documentable_type' => 'required|string',
            'documentable_id' => 'required|integer',
            'file' => 'required|file|max:10240', // 10MB in kilobytes
            'description' => 'nullable|string|max:500',
            'date' => 'required|date',
            'document_type' => 'nullable|string|max:255',
        ]);

        $file = $request->file('file');

        if (! $file->isValid()) {
            return response()->json([
                'success' => false,
                'message' => 'The uploaded file is not valid.',
                'errors' => [
                    'file' => ['The uploaded file is not valid.'],
                ],
            ], 422);
        }

        // Normalize documentable_type
        $documentableType = str_replace('\\\\', '\\', $request->documentable_type);

        // Get file info BEFORE moving (to avoid temp file deletion issues)
        $originalName = $file->getClientOriginalName();
        $extension = $file->getClientOriginalExtension();
        $fileSize = $file->getSize();
        $mimeType = $file->getMimeType();

        // Generate unique filename
        $fileName = Str::random(40) . '.' . $extension;
        
        // Ensure upload directory exists
        $uploadDir = public_path('upload/documents');
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        // Store file
        $filePath = 'upload/documents/' . $fileName;
        $file->move($uploadDir, $fileName);

        // Create document record
        $document = Document::create([
            'documentable_type' => $documentableType,
            'documentable_id' => $request->documentable_id,
            'document_type' => $request->document_type,
            'file_name' => $fileName,
            'original_name' => $originalName,
            'file_path' => $filePath,
            'file_size' => $fileSize,
            'mime_type' => $mimeType,
            'description' => $request->description,
            'date' => $request->date,
            'created_by' => Auth::id(),
        ]);

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

    /**
     * Download a document.
     */
    public function download($id)
    {
        $document = Document::findOrFail($id);
        
        $filePath = public_path($document->file_path);
        
        if (!file_exists($filePath)) {
            return response()->json([
                'success' => false,
                'message' => 'File not found',
            ], 404);
        }

        return response()->download($filePath, $document->original_name);
    }

    /**
     * Display the specified document (view in browser).
     */
    public function show($id)
    {
        $document = Document::findOrFail($id);
        
        $filePath = public_path($document->file_path);
        
        if (!file_exists($filePath)) {
            return response()->json([
                'success' => false,
                'message' => 'File not found',
            ], 404);
        }

        return response()->file($filePath);
    }

    /**
     * Remove the specified document from storage.
     */
    public function destroy($id)
    {
        $document = Document::findOrFail($id);
        
        // Delete physical file
        $filePath = public_path($document->file_path);
        if (file_exists($filePath)) {
            unlink($filePath);
        }

        // Delete database record
        $document->delete();

        return response()->json([
            'success' => true,
            'message' => 'Document deleted successfully',
        ]);
    }
}
