<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\IdDocument;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class IdDocumentController extends Controller
{
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    
    public function store(Request $request)
    {

        $userId = auth()->user()->id;
        // this validation works on api routes

        $validator = Validator::make($request->all(), [
        'file_type' => 'required|in:Passport,Driving License,Proof of Address,Other Document',
        'file_name' => 'required|file|mimes:jpg,jpeg,png,pdf|max:2048',
        'verified'  => 'sometimes|boolean',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors'  => $validator->errors()
            ], 422);
        }

        $fileType = $request->file_type;

        $exist = IdDocument::where('user_id', $userId)
        ->where('file_type', $fileType)
        ->first();
        
        if($exist)
        {
            if($exist->verified === 0)
            {
                return response()->json([
                    'success' => false,
                    'message' => 'the '. $fileType . ' is already exists and not yet verified.'
                ], 400);
            }else{
                return response()->json([
                    'success' => false,
                    'message' => 'the '. $fileType .' is already exists and verified.'
                ], 400);
            }

        }
        // Store the file
        $relativePath = $request->file('file_name')->store('id_documents', 'public'); 

        // $fullPath = asset('storage/' .$relativePath);
        $fullPath = Storage::url($relativePath);

        // Save in database
        $idDocument = IdDocument::create([
            'user_id'   => $userId,
            'file_type' => $request->file_type,
            'file_name' => $request->file('file_name')->getClientOriginalName(),
            'file_path' => url($fullPath),
            'verified'  => 0
        ]);

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




    /**
     * Display the specified resource.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    //  public function index(Request $request){

    //     $userID = auth()->user()->id;
    //     $trading_year = TradingYear::where('user_id', $userID)->first();
    //     $documents = auth()->user()->transactions()
    //          ->where('trading_year_id', $trading_year->id)
    //          ->whereNotNull('attachment')->get();

    //     return response()->json($documents);
    // }
    public function index()
    {

        $userID = auth()->user()->id;
        $id_docs = IdDocument::where('user_id', $userID)->get();
        if (!$id_docs) {
            return response()->json([
                "file_type" => "",
                "file_name" => "",
                "verified" => "",
            ]);
        }

        return response()->json($id_docs);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */

    public function update(Request $request, $id)
    {
        $id_document = IdDocument::find($id);

        if (!$id_document) {
            return response()->json(['error' => 'Record not found'], 404);
        }

        // Validate request
        $request->validate([
            'file_type' => 'sometimes|required|in:Passport,Driving License,Proof of Address,Other Document',
            'file_name' => 'sometimes|file|mimes:jpg,jpeg,png,pdf|max:2048',
            'verified' => 'nullable|in:0,1' // Force it to be provided
        ]);

        // Update file_type
        if ($request->has('file_type')) {
            $id_document->file_type = $request->file_type;
        }

        // Update file if provided
        if ($request->hasFile('file_name')) {
            $file = $request->file('file_name');
            $filePath = auth()->id() . '/' . $file->getClientOriginalName();
            Storage::disk('public')->put($filePath, file_get_contents($file));
            $id_document->file_name = $filePath;
        }

        if ($request->has('verified')) {
        $id_document->verified = (int) $request->verified;
        }
            $id_document->save();

            return response()->json(['message' => 'Id Document updated successfully']);
        }




    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        $id_document = IdDocument::find($id);

        if (!$id_document) {
            return response()->json([
                'success' => false,
                'message' => 'Document not found',
            ], 404);
        }

        // Ensure the document belongs to the authenticated user
        if ($id_document->user_id !== auth()->id()) {
            return response()->json([
                'success' => false,
                'message' => 'You are not authorized to delete this document',
            ], 403);
        }

        // Delete the file from storage if it exists
        if ($id_document->file_name && Storage::disk('public')->exists('id_documents/' . $id_document->file_name)) {
            Storage::disk('public')->delete('id_documents/' . $id_document->file_name);
        }

        // Delete the database record
        $id_document->delete();

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



    // Function to get ID documents for the authenticated user
    public function userDocuments()
    {
        $userId = Auth::id(); // Get the authenticated user's ID

        try {
            // Retrieve ID documents for the authenticated user
            $idDocuments = IdDocument::where('user_id', $userId)->with('user')->get();

            return response()->json($idDocuments);
        } catch (\Exception $e) {
            return response()->json([
                'message' => 'Error retrieving ID documents.',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    public function getFileTypes()
    {
        return response()->json(IdDocument::fileTypes());
    }

     public function download($id)
    {
        $id_doc = IdDocument::find($id);

        if (!$id_doc || !$id_doc->file_path) {
            abort(404, 'No attachment found');
        }

        // Ensure no URL prefix
        $filePath = str_replace(url('storage') . '/', '', $id_doc->file_path);

        // Build correct storage path
        $path = storage_path('app/public/' . $filePath);

        if (!file_exists($path)) {
            return response()->json([
                'error' => 'File not found',
                'checked_path' => $path,
            ], 404);
        }
        // dd( $filePath);

        return response()->download($path);
    }

}