<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Validator;
use Hash;
use Helper;
use Illuminate\Support\Facades\Password;
use App\Model\Profile;

class UserController extends Controller
{
    public function __construct()
    {
        DB::enableQueryLog();
    }

    public function getAll()
    {
        $query = User::select('*', 'users.id as user_id', 'profiles.id as profile_id')->leftJoin('profiles', 'profiles.user_id', 'users.id')->get();

        if($query){
            $result = $query;

            $res_status = true;
            $msg = 'Mendapatkan Data';
            $status_msg = $msg;

            return $this->resSuccess(null, $res_status, $msg, $status_msg, $result);

        }else {

            $res_status = false;
            $msg = 'Data tidak ditemukan';
            $status_msg = $msg;

            return $this->resSuccess(null, $res_status, $msg, $status_msg, null);
        }
    }
    
    public function getSingle($data_id)
    {
        $query = User::select('users.*', 'profiles.*', 'users.id as user_id', 'profiles.id as profile_id', DB::raw('SUM(point_logs.point) as total_point'))->leftJoin('profiles', 'profiles.user_id', 'users.id')->leftJoin('point_logs', 'point_logs.user_id', 'users.id')->where('users.id', Helper::hash($data_id, 'decode'))->get();

        if($query){
            $result = $query;

            $res_status = true;
            $msg = 'Mendapatkan Data';
            $status_msg = $msg;

            return $this->resSuccess(null, $res_status, $msg, $status_msg, $result);

        }else {

            $res_status = false;
            $msg = 'Data tidak ditemukan';
            $status_msg = $msg;

            return $this->resSuccess(null, $res_status, $msg, $status_msg, null);
        }
    }

    public function postLogin(Request $request)
    {        
        $auth = Auth::attempt($request->only('email', 'password'));

        if($auth){
            $result['user'] = Auth::user();

            $res_status = true;
            $msg = 'Mendapatkan Data';
            $status_msg = $msg;

            return $this->resSuccess(null, $res_status, $msg, $status_msg, $result);

        }else {

            $res_status = false;
            $msg = 'Email atau Password yang anda masukkan salah';
            $status_msg = $msg;

            return $this->resSuccess(null, $res_status, $msg, $status_msg, null);
        }
    }

    public function postRegister(Request $request)
    {        
        $validator = Validator::make($request->all(), [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);

        if(!$validator->fails()){
            $result = User::create([
                'name' => $request->name,
                'email' => $request->email,
                'password' => Hash::make($request->password),
                'gambar' => !empty($request->gambar)?Helper::base64_to_image($request->gambar, 'transportation'):'',
            ]);

            $data_role['role_id'] = 2; //driver role
            $result->assignRole($data_role);
            
            // $file = $request->file('photo');
            // if($file){
            //     $user = User::find($result->id);
            //     // $nama_file = time()."_".$file->getClientOriginalName();
            //     // $tujuan_upload = 'photo';
            //     // //$file->move($tujuan_upload,$nama_file);
            //     // Storage::putFileAs('public/photo/user/', $file, $nama_file );
            //     // //File::delete('image/'.$user->photo);
            //     // Storage::delete('public/photo/user/'.$user->photo);
            //     // $user->photo = $nama_file;

            //     $user->save();
            // }

            $res_status = true;
            $msg = 'Berhasil membuat user';
            $status_msg = $msg;

            return $this->resSuccess(null, $res_status, $msg, $status_msg, $result);

        }else {

            $res_status = false;
            $msg = 'Gagal Membuat user';
            $status_msg = $validator->errors();

            return $this->resSuccess(null, $res_status, $msg, $status_msg, null);
        }
    }

    public function postCreateProfile(Request $request)
    {        
        $validator = Validator::make($request->all(), [
            'user_id' => ['required'],
            'fullname' => ['required'],
            'phone_number' => ['required'],
            'gender' => ['required'],
            'is_have_organization' => ['required'],
            'organization_id' => [],
        ]);

        if(!$validator->fails()){
            $result = Profile::create([
                'user_id' => $request->user_id,
                'fullname' => $request->fullname,
                'phone_number' => $request->phone_number,
                'gender' => $request->gender,
                'is_have_organization' => $request->is_have_organization,
                'organization_id' => !empty($request->organization_id)?$request->organization_id:NULL,
            ]);

            $res_status = true;
            $msg = 'Berhasil membuat user';
            $status_msg = $msg;

            return $this->resSuccess(null, $res_status, $msg, $status_msg, $result);

        }else {

            $res_status = false;
            $msg = 'Gagal Membuat user';
            $status_msg = $validator->errors();

            return $this->resSuccess(null, $res_status, $msg, $status_msg, null);
        }
    }

    public function postUpdateProfile(Request $request)
    {        
        $validator = Validator::make($request->all(), [
            'user_id' => ['required'],
            'fullname' => ['required'],
            'phone_number' => ['required'],
            'gender' => ['required'],
            'is_have_organization' => ['required'],
            'organization_id' => [],
        ]);

        if(!$validator->fails()){
            $profile = Profile::where('user_id', $request->user_id)->firstOrFail();
            
            $profile->user_id = $request->user_id;
            $profile->fullname = $request->fullname;
            $profile->phone_number = $request->phone_number;
            $profile->gender = $request->gender;
            $profile->is_have_organization = $request->is_have_organization;
            $profile->organization_id = !empty($request->organization_id)?$request->organization_id:'';

            $res_status = true;
            $msg = 'Berhasil membuat user';
            $status_msg = $msg;

            return $this->resSuccess(null, $res_status, $msg, $status_msg, $result);

        }else {

            $res_status = false;
            $msg = 'Gagal Membuat user';
            $status_msg = $validator->errors();

            return $this->resSuccess(null, $res_status, $msg, $status_msg, null);
        }
    }

    public function postForgotPassword() {
        $credentials = request()->validate(['email' => 'required|email']);

        Password::sendResetLink($credentials);

        return response()->json(["msg" => 'Reset password link sent on your email id.']);
    }

    public function postResetPassword() {
        $credentials = request()->validate([
            'email' => 'required|email',
            'token' => 'required|string',
            'password' => 'required|string|confirmed'
        ]);

        $reset_password_status = Password::reset($credentials, function ($user, $password) {
            $user->password = $password;
            $user->save();
        });

        if ($reset_password_status == Password::INVALID_TOKEN) {
            return response()->json(["msg" => "Invalid token provided"], 400);
        }

        return response()->json(["msg" => "Password has been successfully changed"]);
    }
    
    public function resSuccess($param = null, $status = null, $msg = null, $status_msg = null, $result = null)
    {
        $response['response'] = array(
            'status'     => $status,
            'message'    => $msg,
            'status_msg' => $status_msg,
        );
        $response['param'] = !empty($param) ? $param : '';

        $response['results'] = $result;

        return response()->json($response, 200);
    }

}
