<?php

namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\ClientDocument;
use Illuminate\Support\Facades\Storage;

class ClientDocumentController extends Controller
{
    public function upload(Request $request)
    {
        $request->validate([
            'file' => 'required|file|max:10240|mimes:pdf,jpg,jpeg,png,doc,docx,txt,ppt,pptx',
            'documentName' => 'required|string|max:255',
            'documentType' => 'required|string|max:50',
            'description' => 'nullable|string',
            'clientId' => 'required|exists:clients,id',
        ]);

        $file = $request->file('file');
        $path = $file->store("client_documents/{$request->clientId}", 'public');

        $doc = ClientDocument::create([
            'client_id' => $request->clientId,
            'filename' => $file->getClientOriginalName(),
            'file_path' => $path,
            'file_type' => $file->getClientMimeType(),
            'description' => $request->description,
            'uploaded_by' => auth()->id() ?? 1,
        ]);

        return response()->json([
            'message' => 'File uploaded successfully',
            'document' => $doc
        ], 201);
    }
 public function clientdocuments($clientId)
{
    $documents = ClientDocument::where('client_id', $clientId)
        ->with('uploader')
        ->orderBy('created_at', 'desc')
        ->get()
        ->map(function ($doc) {
            $doc->file_url = $doc->file_name
                ? asset('storage/client_documents/' . $doc->file_name)
                : null;
            return $doc;
        });

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


}
