<?php

namespace App\Http\Controllers\api\v1;

use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\BaseController;

class FollowControllerREST extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $query = DB::table('follows')
            ->select('follows.*', 'users.first_name', 'users.last_name')
            ->leftJoin('users', 'users.id', '=', 'follows.related_id')
            ->where('follows.user_id', Auth::user()->id)
            ->orderBy('follows.created_at', 'desc');

        $query = $query->paginate(request()->get('limit', 20));

        $response = [
            'success'      => true,
            'data'         => $query->getCollection()->toArray(),
            'total'        => $query->total(),
            'current_page' => $query->currentPage(),
            'last_page'    => $query->lastPage(),
        ];

        return Response::json($response);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store()
    {
        $data = request()->all();
        $data['user_id'] = Auth::user()->id;

        $follow = DB::table('follows')->insert([
            'user_id' => $data['user_id'],
            'related_id' => $data['related_id'],
            'related_type' => $data['related_type'],
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return Response::json(['success' => true, 'message' => 'Follow created']);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        $follow = DB::table('follows')
            ->select('follows.*', 'users.first_name', 'users.last_name')
            ->leftJoin('users', 'users.id', '=', 'follows.related_id')
            ->where('follows.id', $id)
            ->where('follows.user_id', Auth::user()->id)
            ->first();

        if (!$follow) {
            return Response::json(['error' => 'Follow not found'], 404);
        }

        return Response::json($follow);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        $follow = DB::table('follows')
            ->where('id', $id)
            ->where('user_id', Auth::user()->id)
            ->first();

        if (!$follow) {
            return Response::json(['error' => 'Follow not found'], 404);
        }

        DB::table('follows')->where('id', $id)->delete();

        return Response::json(['success' => true, 'message' => 'Follow deleted']);
    }
}
