<?php

namespace App\Http\Controllers\v1;

use Illuminate\Http\Request;
use App\WorkOrder;
use App\Customer;
use App\Product;
use App\WorkOrderVisit;
use App\DuplicateTest;
use Illuminate\Routing\Controller as BaseController;

class ToolsController extends BaseController
{
	
	public function removeDuplicatedVisits()
	{
		
		$arrWorkOrderVisits = array();
		$arrWorkOrderVisitsDuplicated = array();
		
		$work_order_visits = WorkOrderVisit::whereDate('date', '>', date('Y-m-d'))
												->orderBy('work_order_id', 'ASC')
													->orderBy('date', 'ASC')
														->get();
													
		foreach ($work_order_visits as $work_order_visit) {
			
			$key = $work_order_visit->work_order_id . '--' . $work_order_visit->date;
			
			if (!in_array($key, $arrWorkOrderVisits)) {
				$arrWorkOrderVisits[] = $key;
			} else {
				
				$arrWorkOrderVisitsDuplicated[] = array(
					'id' => $work_order_visit->id,
					'company_id' => $work_order_visit->company_id,
					'work_order_id' => $work_order_visit->work_order_id,
					'date' => $work_order_visit->date
				);
				
				$work_order_visit->delete();
				
			}
			
		}
		
		echo 'TOTAL: ' . count($arrWorkOrderVisitsDuplicated) . '<br />';
		print_r($arrWorkOrderVisitsDuplicated);
		
	}
	
	private function _isDuplicateEntryException(\Exception $e)
	{
		
		$sqlState = $e->errorInfo[0];
		$errorCode = $e->errorInfo[1];
		
		echo $sqlState . '/' . $errorCode;
		
		if ($sqlState === "23000" && $errorCode === 1062) {
			return true;
		}
		
		return false;
		
	}
	
	public function duplicateTest(Request $request)
	{
		
		$created = false;
		
		try {
			
			$duplicate_test = new DuplicateTest();
			$duplicate_test->name = $request->name;
			$duplicate_test->email = $request->email;
			
			if ($duplicate_test->save()) {
				$created = true;
			}
			
		} catch (\Exception $e) {
			//
		}
		
		if ($created) {
			echo 'CREATED';
		} else {
			echo 'NOT CREATED';
		}
		
	}

}
