<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Validator;
use Hidehalo\Nanoid\Client as Nanoid;
use GuzzleHttp\Client as GuzzleClient;
use App\Responses;
use App\Helper;

class StorageController extends Controller
{

  public function save_photos(Request $req)
	{

		$url_photos_base64 = [];
		try {
			$now = time();

			$input = [
				'names' => $req->names,
				'photos' => $req->photos,
			];
			$rulesInput = [
        'names' => 'required|array',
        'names.*' => 'required|string|max:255',
				'photos' => 'required|array',
        'photos.*' => 'required|string',
			];

			// validasi input
			$isValidInput = Validator::make($input, $rulesInput);
			if (!$isValidInput->passes()) {
				$apiResp = Responses::bad_input($isValidInput->messages()->first());
				return new Response($apiResp, $apiResp['meta']['code']);
			}

      if ($req->names && count($req->names) < 1) {
				$apiResp = Responses::bad_input('names is required');
				return new Response($apiResp, $apiResp['meta']['code']);
			}
			if ($req->photos && count($req->photos) < 1) {
				$apiResp = Responses::bad_input('photos is required');
				return new Response($apiResp, $apiResp['meta']['code']);
			}

			foreach ($req->photos as $i => $img) {
        $clearBase64 = preg_replace('/^data:(image|application)\/(png|jpg|jpeg|pdf);base64,/', '', $img);
        // $type = 'jpeg';
        // if (strpos($img, 'application/pdf') !== false) $type = 'pdf';
        // $url_photos_base64[$i] = "orders/" . $order[0]->ord_id . "/a_items/" . $oa_id . "/submission/" . $req->auth->uid . "/submission_proof_img_$now" . "_" . "$i.$type";
        $url_photos_base64[$i] = $req->names[$i];
        if (!Storage::disk('public')->put($url_photos_base64[$i], base64_decode($clearBase64))) {
          $apiResp = Responses::bad_request('fail save photo');
          return (new Response($apiResp, $apiResp['meta']['code']));
        }
      }

			$apiResp = Responses::success('success save photos');
			return (new Response($apiResp, $apiResp['meta']['code']));
		} catch (\Exception $e) {
			if (count($url_photos_base64) > 0) {
				foreach ($url_photos_base64 as $path) {
					Storage::disk('public')->delete($path);
				}
			}
			$apiResp = Responses::error($e->getMessage());
			return (new Response($apiResp, $apiResp['meta']['code']));
		}
	}

}