<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\Rule;
use App\Models\User;
use App\Models\Package;
use Spatie\Permission\Models\Role;
use App\Http\Helper\Helper;
use Hash;

class ClientController extends Controller
{
    /**
    * Retrun contacts
    */
    public function getClients(Request $request): JsonResponse
    {
        $result = User::select('users.id', 'users.name', 'users.email', 'users.is_active', 'users.created_at', 'packages.name as package_name', 'packages.id as package_id')
          ->leftJoin('packages', 'users.package_id', '=', 'packages.id')
          ->where('users.is_client', 1) 
          ->where('packages.app_id', $request->user('api')->app_id)
          ->with('roles')
          ->where('users.id', '<>', 1); // avoid to get superadmin as came with installation


        if(!empty($request->start_from))
          $result->offset($request->start_from);

        $limit = !empty($request->limit) ? $request->limit : 100; 
        
        $data = $result->limit($limit)->get();

        return Helper::apiReturn(__('app.success'), $data);
    }

    /**
    * Retrun a contact detail
    */
    public function get(Request $request, $id): JsonResponse
    {
        $data = User::select('users.id', 'users.name', 'users.email', 'users.is_active', 'users.created_at', 'packages.name as package_name', 'packages.id as package_id')
          ->leftJoin('packages', 'users.package_id', '=', 'packages.id')
          ->where('users.id', $id)
          ->where('users.is_client', 1)
          ->where('packages.app_id', $request->user('api')->app_id)   
          ->with('roles')                 
          ->first();

        if(!empty($data)) {
          $status = __('app.success');
        } else {
          $status = __('app.error');
          $data = ['message' => __('app.no_record_found')];
        }

        return Helper::apiReturn($status, $data);
    }

    /**
    * Add a contact
    */
    public function add(Request $request): JsonResponse
    {
        $input = $this->_contactData($request);
        $status = __('app.error');
        if(empty($input['name'])) {
          $data = [
            'message' => 'name ' . __('app.is_required'),
          ];
        } elseif(empty($input['email']) || !filter_var($input['email'], FILTER_VALIDATE_EMAIL)) {
          $data = [
            'message' => 'valid email ' . __('app.is_required'),
          ];
        } elseif(empty($input['role_id'])) {
          $data = [
            'message' => 'role_id ' . __('app.is_required'),
          ];
        } elseif(!Role::whereId($input['role_id'])->whereAppId($input['app_id'])->exists()) {
          $data = [
            'message' => 'role_id ' . __('app.not_exist'),
          ];
        } elseif(empty($input['package_id'])) {
          $data = [
            'message' => 'package_id ' . __('app.is_required'),
          ];
        } elseif(!Package::whereId($input['package_id'])->whereAppId($input['app_id'])->exists()) {
          $data = [
            'message' => 'package_id ' . __('app.not_exist'),
          ];
        } else {
          $input = $request->all();
          $input['password'] = Hash::make($input['password']);
          // overwrite app_id
          $input['app_id'] = User::max('app_id')+1;
          $input['parent_id'] = $request->user('api')->id;
          $input['is_client'] = 1;
      
          $data = User::create($input);
          $data['role_id'] = $input['role_id'];

          $role_name = Role::where('id', $input['role_id'])->pluck('name')->first();
          $data->assignRole(Role::where('name', trim($role_name))->firstOrFail());

          // save log
          activity('create')->withProperties(['app_id' => $input['app_id']])->log(__('app.client') . " ({$data->name}) ". __('app.log_create'));
          $status = __('app.success');
        }

        return Helper::apiReturn($status, $data);
    }

    /**
    * Update a contact 
    */
    public function update(Request $request, $id): JsonResponse
    {
        $input = $this->_contactData($request);
        $status = __('app.error');
        if(!empty($input['email']) && !filter_var($input['email'], FILTER_VALIDATE_EMAIL)) {
          $data = [
            'message' => 'valid email ' . __('app.is_required'),
          ];
        } elseif(!empty($input['role_id']) && !Role::whereId($input['role_id'])->whereAppId($input['app_id'])->exists()) {
          $data = [
            'message' => 'role_id ' . __('app.not_exist'),
          ];
        } elseif(!empty($input['package_id']) && !Package::whereId($input['package_id'])->whereAppId($input['app_id'])->exists()) {
          $data = [
            'message' => 'package_id ' . __('app.not_exist'),
          ];
        } else {
          $data = User::findOrFail($id);
          $input['password'] = Hash::make($input['password']);
          $data->fill($input)->save();

          if(!empty($input['role_id'])) {
            $role_name = Role::where('id', $input['role_id'])->pluck('name')->first();
            $data->assignRole(Role::where('name', trim($role_name))->firstOrFail());
          }

          // save log
          activity('update')->withProperties(['app_id' => $input['app_id']])->log(__('app.client') . " ({$data->name}) ". __('app.log_update'));
          $status = __('app.success');
        }

        return Helper::apiReturn($status, $data);
    }

    /**
    * Return inputed data
    */
    public function _contactData($request)
    {
        $input = $request->all();
        $input['email'] = !empty($input['email']) ? trim($input['email']) : null;
        $input['source'] = 'api';
        $input['user_id'] = $request->user('api')->id;
        $input['app_id'] = $request->user('api')->app_id;
        return $input;
    }

    /**
    * Delete a contact
    */
    public function destroy(Request $request, $id): JsonResponse
    {
        $name = User::whereId($id)->value('name');
        if(!empty($name)) {
          $destroy = User::destroy($id);
          activity('delete')->withProperties(['app_id' => $request->user('api')->app_id])->log(__('app.contact') . " ({$name}) ". __('app.log_delete'));

          $status = __('app.success');
          $data = [
            'id' => $id,
            'name' => $name
          ];
        } else {
          $status = __('app.error');
          $data = ['message' => __('app.no_record_found')];
        }
        return Helper::apiReturn($status, $data);
    }
}
