<?php
/**
 * Created by PhpStorm.
 * User: user pc
 * Date: 11/1/2018
 * Time: 12:38 AM
 */

namespace App\Http\Traits;


use App\Models\SmsRate;
use App\Models\User;
use App\Models\Account;
use App\Models\Log;
use App\Models\Payment;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
use League\Flysystem\Config;

trait ResponseTrait
{

    protected function paginateResponse ($data, $perPage = 6) {
        $page = LengthAwarePaginator::resolveCurrentPage();

        $results = collect($data)->slice(($page - 1) * $perPage, $perPage)->values();

//        $results = $collection->slice(($page - 1) * $perPage, $perPage)->values();

        $paginated = new LengthAwarePaginator($results, count($data), $perPage, $page, [
            'path' => LengthAwarePaginator::resolveCurrentPath(),
        ]);

        $paginated->appends('data', $data);

        return $paginated;
    }

    protected function successResponse($data, $message = 'ok') {

        $response = [
            'code' => 200,
            'error' => false,
            'status' => 'success',
            'message' => $message,
            'data' => $data
        ];
        return response()->json($response, 200, [], JSON_NUMERIC_CHECK);
    }
    
    protected function notFoundResponse() {

        $response = [
            'code' => 404,
            'error' => true,
            'status' => 'error',
            'message' => 'Resource Not Found'
        ];
        return response()->json($response, 404);
    }

    protected function resultsNotFoundResponse($message) {

        $response = [
            'code' => 200,
            'error' => true,
            'status' => 'error',
            'message' => $message
        ];
        return response()->json($response, 404);
    }

    protected function updateResponse($message) {

        $response = [
            'code' => 200,
            'error' => false,
            'status' => 'success',
            'message' => $message
        ];
        return response()->json($response, 201);
    }

    public function deleteResponse($message) {

        $response = [
            'error' => false,
            'status' => 'success',
            'data' => [],
            'message' => $message
        ];
        return response()->json($response, 200);
    }

    public function errorResponse($message) {

        $response = [
            'code' => 200,
            'error' => true,
            'status' => 'error',
            'message' => $message
        ];
        return response()->json($response, 500);
    }

    /**
     * Format paginated response with meta wrapper
     */
    protected function paginatedResponse($paginator, $message = 'Data retrieved successfully', $additionalMeta = [])
    {
        $response = [
            'code' => 200,
            'error' => false,
            'status' => 'success',
            'message' => $message,
            'data' => $paginator->items(),
            'meta' => array_merge([
                'current_page' => $paginator->currentPage(),
                'per_page' => $paginator->perPage(),
                'total' => $paginator->total(),
                'last_page' => $paginator->lastPage(),
                'from' => $paginator->firstItem(),
                'to' => $paginator->lastItem(),
                'path' => $paginator->path(),
                'first_page_url' => $paginator->url(1),
                'last_page_url' => $paginator->url($paginator->lastPage()),
                'next_page_url' => $paginator->nextPageUrl(),
                'prev_page_url' => $paginator->previousPageUrl(),
            ], $additionalMeta),
        ];

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

    protected function randomString($len){
        $result = "";
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $charArray = str_split($chars);
        for($i = 0; $i < $len; $i++){
            $randItem = array_rand($charArray);
            $result .= "".$charArray[$randItem];
        }
        return $result;
    }

    protected function randomNumber($len){
        $result = "";
        $chars = "0123456789";
        $charArray = str_split($chars);
        for($i = 0; $i < $len; $i++){
            $randItem = array_rand($charArray);
            $result .= "".$charArray[$randItem];
        }
        return $result;
    }

    protected function getSmsRate ($number) {

        $rate = 'Not defined';

        $rates = SmsRate::where('min_messages', '<=', $number)->where('max_messages', '>=', $number)->get()->first();

        if ($rates) {
            $rate = $rates->rate;
        }

        return $rate;
    }

    public static function createSlug($str, $delimiter = '-'){

        $slug = strtolower(trim(preg_replace('/[\s-]+/', $delimiter, preg_replace('/[^A-Za-z0-9-]+/', $delimiter, preg_replace('/[&]/', 'and', preg_replace('/[\']/', '', iconv('UTF-8', 'ASCII//TRANSLIT', $str))))), $delimiter));
        return $slug;

    } 

}