<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;

class DocumentsController extends Controller
{
    public function store(Request $request)
    {
        // 1. Validate the incoming request
        $request->validate([
            'file' => 'required|file|max:10240', // 10MB
            'type' => 'required|string',
        ]);

        // 2. Store locally on your ERP server
        $file = $request->file('file');
        $originalName = $file->getClientOriginalName();
        $localPath = $file->storeAs('documents/' . date('Y/m'), $originalName, 'local');

        // 3. Check if it needs to be pushed to Paperless-Ngx
        // You can base this on the checkbox OR force it based on type (e.g., $request->type === 'contract')
        if ($request->boolean('push_to_paperless')) {
            $this->pushToPaperless($localPath, $originalName, $request->all());
        }

        return response()->json(['message' => 'Document saved successfully.']);
    }
    public function storeTwo(Request $request)
    {
        // ... validation and local storage logic ...
        $localPath = $file->storeAs('documents/' . date('Y/m'), $originalName, 'local');

        // Retrieve the actual Eloquent models based on the form input
        $entity = MnoPartner::find($request->input('entity_id')); 
        $docType = DocumentType::where('slug', $request->input('type'))->first();

        if ($request->boolean('push_to_paperless')) {
            // Dispatch the job to the queue
            PushDocumentToPaperless::dispatch(
                $localPath,
                $originalName,
                $entity,
                $docType,
                $request->input('notes')
            );
        }

        return response()->json(['message' => 'Document saved and queued for archival.']);
    }

    private function pushToPaperless(string $localPath, string $fileName, array $metadata)
    {
        $paperlessUrl = env('PAPERLESS_URL'); 
        $apiToken = env('PAPERLESS_API_TOKEN');

        try {
            // Get the raw file contents from local storage
            $fileContents = Storage::disk('local')->get($localPath);

            // Send to Paperless-Ngx /api/documents/post_document/ endpoint
            $response = Http::withToken($apiToken)
                ->attach(
                    'document', 
                    $fileContents, 
                    $fileName
                )
                ->post("{$paperlessUrl}/api/documents/post_document/", [
                    // Optional Paperless metadata fields
                    'title' => $metadata['notes'] ?? $fileName,
                    // You can map ERP tags to Paperless Tag IDs here
                    // 'tags' => [1, 4], 
                    // 'correspondent' => 2 
                ]);

            if (!$response->successful()) {
                Log::error('Paperless-Ngx Upload Failed', ['error' => $response->body()]);
            }

        } catch (\Exception $e) {
            Log::error('Paperless-Ngx Connection Error', ['message' => $e->getMessage()]);
        }
    }
}