<?php

namespace App\Http\Controllers\Api\Auth;

use App\Http\Controllers\Controller;
use App\Models\Listing;
use App\Models\ListingNotes;
use Illuminate\Http\Request;

class ListingNoteController extends Controller
{
    public function index(Request $request)
    {
        $this->is_user($request);

        $user = $request->user();

        $notes = ListingNotes::query()
            ->where('user_id', $user->id)
            ->with(['listing', 'listing.coverImage', 'listing.category', 'user'])
            ->latest()
            ->get();

        return response()->json([
            'data' => $notes
        ]);
    }


    public function show(Request $request, Listing $listing)
    {
        $this->is_user($request);

        $user = $request->user();

        $notes = ListingNotes::query()
            ->where('user_id', $user->id)
            ->where('listing_id', $listing->id)
            ->with(['listing', 'listing.coverImage', 'listing.category', 'user'])
            ->latest()
            ->get();

        return response()->json([
            'data' => $notes
        ]);
    }


    public function store(Request $request, Listing $listing)
    {
        $this->is_user($request);

        $data = $request->validate([
            'note' => ['required', 'string', 'max:350']
        ]);


        $created_note = ListingNotes::updateOrCreate(
            [
                'listing_id' => $listing->id,
                'user_id' => $request->user()->id
            ],
            [
                'note' => $data['note']

            ]
        );

        return response()->json([
            'id' => $created_note->id
        ]);
    }


    public function delete(Request $request, Listing $listing)
    {
        $this->is_user($request);

        ListingNotes::query()
        ->where('listing_id',$listing->id)
        ->where('user_id',$request->user()->id)
        ->delete();

        return response()->json([
            'message' => 'silme işlemi tamamlandı'
        ]);
    }









    private function is_user(Request $request)
    {
        abort_unless($request->user(), 403, 'İlanlara aldığınız notları görebilmek için giriş yapınız');
    }
}
