<?php

namespace Modules\SystemCore\App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Storage;
use Modules\SystemCore\App\Http\Requests\StoreSupplierDocumentRequest;
use Modules\SystemCore\App\Http\Requests\UpdateSupplierDocumentRequest;
use Modules\SystemCore\App\Models\CoreSupplier;
use Modules\SystemCore\App\Models\SupplierDocument;
use Symfony\Component\HttpFoundation\StreamedResponse;

class SupplierDocumentController extends Controller
{
    /**
     * Store a newly created supplier document in storage.
     */
    public function store(StoreSupplierDocumentRequest $request, int $supplier): JsonResponse
    {
        $supplierModel = CoreSupplier::findOrFail($supplier);
        $validatedData = $request->validated();

        // Handle file upload
        if ($request->hasFile('document_file')) {
            $file = $request->file('document_file');
            $path = $file->store("supplier-documents/{$supplierModel->id}", 'public');

            $validatedData['supplier_id'] = $supplierModel->id;
            $validatedData['file_path'] = $path;
            $validatedData['file_name'] = $file->getClientOriginalName();
            $validatedData['mime_type'] = $file->getMimeType();
            $validatedData['file_size'] = $file->getSize();
        }

        // Remove the document_file from validated data as we've processed it
        unset($validatedData['document_file']);

        $document = SupplierDocument::create($validatedData);

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

    /**
     * Display the specified supplier document for editing.
     */
    public function show(int $supplier, int $document): JsonResponse
    {
        $supplierModel = CoreSupplier::findOrFail($supplier);
        $documentModel = SupplierDocument::where('id', $document)
            ->where('supplier_id', $supplier)
            ->firstOrFail();

        return response()->json([
            'success' => true,
            'data' => [
                'id' => $documentModel->id,
                'document_title' => $documentModel->document_title,
                'document_number' => $documentModel->document_number,
                'document_type' => $documentModel->document_type,
                'file_name' => $documentModel->file_name,
                'file_url' => $documentModel->file_url,
                'mime_type' => $documentModel->mime_type,
                'file_size' => $documentModel->file_size,
                'formatted_file_size' => $documentModel->formatted_file_size,
                'issue_date' => $documentModel->issue_date?->format('Y-m-d'),
                'expiry_date' => $documentModel->expiry_date?->format('Y-m-d'),
                'notes' => $documentModel->notes,
                'is_active' => $documentModel->is_active,
                'is_expired' => $documentModel->isExpired(),
            ],
        ]);
    }

    /**
     * Update the specified supplier document in storage.
     */
    public function update(UpdateSupplierDocumentRequest $request, int $supplier, int $document): JsonResponse
    {
        $supplierModel = CoreSupplier::findOrFail($supplier);
        $documentModel = SupplierDocument::where('id', $document)
            ->where('supplier_id', $supplier)
            ->firstOrFail();

        $validatedData = $request->validated();

        // Handle file upload if a new file is provided
        if ($request->hasFile('document_file')) {
            // Delete old file if it exists
            if ($documentModel->file_path) {
                Storage::disk('public')->delete($documentModel->file_path);
            }

            $file = $request->file('document_file');
            $path = $file->store("supplier-documents/{$supplierModel->id}", 'public');

            $validatedData['file_path'] = $path;
            $validatedData['file_name'] = $file->getClientOriginalName();
            $validatedData['mime_type'] = $file->getMimeType();
            $validatedData['file_size'] = $file->getSize();
        }

        // Remove the document_file from validated data as we've processed it
        unset($validatedData['document_file']);

        $documentModel->update($validatedData);

        return response()->json([
            'success' => true,
            'message' => __('Document updated successfully.'),
            'data' => $documentModel->fresh(),
        ]);
    }

    /**
     * Remove the specified supplier document from storage.
     */
    public function destroy(int $supplier, int $document): JsonResponse
    {
        $supplierModel = CoreSupplier::findOrFail($supplier);
        $documentModel = SupplierDocument::where('id', $document)
            ->where('supplier_id', $supplier)
            ->firstOrFail();

        // Delete the file from storage
        if ($documentModel->file_path) {
            Storage::disk('public')->delete($documentModel->file_path);
        }

        // Delete the document record
        $documentModel->delete();

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

    /**
     * Download the specified supplier document.
     */
    public function download(int $supplier, int $document): StreamedResponse
    {
        $supplierModel = CoreSupplier::findOrFail($supplier);
        $documentModel = SupplierDocument::where('id', $document)
            ->where('supplier_id', $supplier)
            ->firstOrFail();

        if (! $documentModel->file_path || ! Storage::disk('public')->exists($documentModel->file_path)) {
            abort(404, __('Document file not found.'));
        }

        // Build filename for download
        $fileName = str_replace(' ', '_', $documentModel->document_title);
        if ($documentModel->document_number) {
            $fileName .= "_{$documentModel->document_number}";
        }

        // Determine file extension
        $extension = pathinfo($documentModel->file_path, PATHINFO_EXTENSION);
        if (! $extension) {
            // Default based on mime type if extension isn't in the path
            $extension = match ($documentModel->mime_type) {
                'application/pdf' => 'pdf',
                'image/jpeg' => 'jpg',
                'image/png' => 'png',
                'application/msword' => 'doc',
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
                default => 'pdf',
            };
        }

        $fileName .= '.'.$extension;

        return Storage::disk('public')->download($documentModel->file_path, $fileName);
    }
}
