<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;

use App\CallLog;
use App\Traits\CallLogTrait;

use DB;

class CallLogController extends Controller
{

	use CallLogTrait;

	private $debug;

	public function __construct(Request $request)
	{
		if($request->has('debug') && $request->input('debug') == true) {
			$this->debug = true;
		}
	}

	public function getCallLog(Request $request)
	{
		$callLogs = CallLog::where('id', '>', 0)
		->orderBy('id', 'DESC')
		->paginate(10);

		return $callLogs;
	}

	public function storeCallLog(Request $request)
	{	
		$callLogs = array();
		$callLogIds = array();

		if($request->has('data')) {
			$callLogs = $request->input('data');

			foreach($callLogs as $data) {
				$callLogIds[] = $this->insertCallLog($data);
			}

			return new JsonResponse(
				array(
					"status#"		=>	"1",
					"msg#"			=> 	"Call log(s) stored successfully!"
				)
			);
		}

		return new JsonResponse(
			array(
				"status#"		=>	"1",
				"msg#"			=> 	"No records to insert!"
			)
		);

	}

	public function updateCallLog(Request $request)
	{

	}

	public function deleteCallLog(Request $request)
	{
		
	}

	public function playRecording($id = 0)
	{
		$callLog = CallLog::find($id);

		if(!$callLog) {
			return Response::json([
				'status' 	=>	'error',
				'msg' 		=>	'Record not found!'
			], 200);
		}

		if(!$callLog['call_recordpath']) {
			return Response::json([
				'status' 	=>	'error',
				'msg' 		=>	'Recorded file not found!'
			], 200);
		}

		if(!Storage::disk('local')->has($callLog['call_recordpath'])) {
			return Response::json([
				'status' 	=>	'error',
				'msg' 		=>	'Recorded file does not exists!'
			], 200);
		}

		$file = Storage::disk('local')->get($callLog['call_recordpath']);

		return response($file, 200)
                  ->header('Content-Type', 'audio/amr');
	}

}