<?php
namespace App\Http\Controllers\Api\v1;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Activity;

/**
 * ActivityController Class Doc Comment
 *
 * @category Class
 * @package  Api
 * @author   Ketan Patel - ketan.patel@brainvire.com
 *
*/
class ActivityController extends Controller
{

    public function __construct()
    {
     //$this->middleware('oauth', ['except' => ['index']]);
     //$this->middleware('auth:api', ['except' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $activity = Activity::all();
        
        $helperObj = new \App\CommonHelper();
        $dateformat = env("DATE_FORMAT");
        $timeformat = env("TIME_FORMAT");
        if (!empty($activity)) {
            foreach($activity as $key => $val){
                $activity[$key]->created = $helperObj->convertDateByFormat($val->created, $dateformat.' '.$timeformat);
            }
        }
        
        return response()->json($activity);
    }
    
    
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function filterByDate(Request $request)
    {
        $this->validate($request, [
            'startDate'  => 'required|date|date_format:Y/m/d',
            'endDate'    => 'required|date|date_format:Y/m/d',
        ]);
        
        
        $tempStartDate  = $request->startDate;
        $tempEndDate    = $request->endDate;
        $activity       = array();
        
        if ($tempStartDate!='' && $tempEndDate!='') {
            $sdate     = new \DateTime($tempStartDate);
            $startDate = date('Y-m-d 00:00:00',strtotime($tempStartDate));
            $endDate   = date('Y-m-d 23:59:59',strtotime($tempEndDate));
            
            if ($startDate!=$endDate) {
                $activity = DB::table('activities')
                    ->where('created', '>=', $startDate)
                    ->where('created', '<=', $endDate)
                    ->get();
            } else {
                $startDateOnly         = $sdate->format('Y-m-d');
                $activity = DB::table('activities')
                    ->where('created', 'LIKE', '%'.$startDateOnly.'%')
                    ->get();
            }
        }
        return response()->json($activity);
    }
    
     /**
     * Get the specified resource from storage.
     *
     * @param  int $rid
     * @return \Illuminate\Http\Response
     */
    public function show($rid)
    {
        $activities = Activity::all()->where('user_id', $rid);
        if (count($activities) > 0) {
            return response()->json($activities);
        } else {
            return response()->json(['status' => 'fail']);
        }
    }
}
