<?php

namespace App\Http\Controllers;

use App\Models\ProjectFollowRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ProjectFollowRequestController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'project_id' => 'required|exists:projects,id',
        ]);

        // Pastikan pengguna tidak mengajukan permintaan untuk proyek yang sudah mereka ikuti
        $existingRequest = ProjectFollowRequest::where('user_id', Auth::id())
            ->where('project_id', $request->input('project_id'))
            ->first();

        if ($existingRequest) {
            return response()->json(['message' => 'Follow request already exists.'], 400);
        }

        // Buat permintaan untuk mengikuti proyek
        ProjectFollowRequest::create([
            'user_id' => Auth::id(),
            'project_id' => $request->input('project_id'),
        ]);

        return response()->json(['message' => 'Follow request submitted.'], 200);
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'status' => 'required|in:approved,rejected',
        ]);

        $followRequest = ProjectFollowRequest::findOrFail($id);

        // Hanya pemilik proyek yang dapat mengupdate status
        $project = $followRequest->project;
        if (Auth::id() !== $project->user_id) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $followRequest->update(['status' => $request->input('status')]);

        // Jika disetujui, tambahkan entri di tabel interaksi pengguna-proyek
        if ($request->input('status') === 'approved') {
            // Logika untuk menambahkan interaksi, jika diperlukan
        }

        return response()->json(['message' => 'Follow request updated.'], 200);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
