<?php

include('connect.php');

use Swagger\Client\ApiException;



// echo $_SERVER['REMOTE_ADDR'];



$query1  = "SELECT DISTINCT tyres1.width FROM tyres1 ORDER BY tyres1.width"; 

$result1 = $conn->query ($query1);



$query2  = "SELECT DISTINCT tyres1.profile FROM tyres1 ORDER BY tyres1.profile"; 

$result2 = $conn->query ($query2);



$query3  = "SELECT DISTINCT tyres1.diameter FROM tyres1 ORDER BY tyres1.diameter"; 

$result3 = $conn->query ($query3);



$query4  = "SELECT DISTINCT tyres1.speed FROM tyres1 ORDER BY tyres1.speed"; 

$result4 = $conn->query ($query4);



if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_POST)) {

require_once('vendor/autoload.php');



// // SMSWorks API credentials

$accountKey = 'd0a3bb5b-1928-45b8-aada-d2f7cd0b2b55';

$accountSecret = 'f4dcb37a4361e9ba09b29bed895473db886d29565745cafb783c37b6166388f3';

$auth_token = 'JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXkiOiJkMGEzYmI1Yi0xOTI4LTQ1YjgtYWFkYS1kMmY3Y2QwYjJiNTUiLCJzZWNyZXQiOiJmNGRjYjM3YTQzNjFlOWJhMDliMjliZWQ4OTU0NzNkYjg4NmQyOTU2NTc0NWNhZmI3ODNjMzdiNjE2NjM4OGYzIiwiaWF0IjoxNjc4MTUwNDAxLCJleHAiOjI0NjY1NTA0MDF9.QQkQ90FCI4XInWQeKo8stS3im9sagQD1ufPhCOT7EZ8';



// // Form data

$name = addslashes($_POST['name']);

$phone = addslashes($_POST['phone']);

$door = addslashes($_POST['door']);

$postcode = addslashes($_POST['postcode']);

$width = addslashes($_POST['width']);

$profile = addslashes($_POST['profile']);

$diameter = addslashes($_POST['diameter']);

// $speed = addslashes($_POST['speed']);

$quantity = addslashes($_POST['quantity']);

$brand = addslashes($_POST['brand']);

$price = addslashes($_POST['price']);

$notes = addslashes($_POST['notes']);

$registration = addslashes($_POST['registration']);

$lwn_label = 'I confirm I have my locking wheel nut available';
$lwn_available = isset($_POST['locking_wheel_nut']) ? 'Yes' : 'No';

$size = $width." /".$profile." R".$diameter;



$smsContent = $_POST;



unset($smsContent['width']);

unset($smsContent['profile']);

unset($smsContent['diameter']);



$smsContent['size'] = $size;



$totalPrice = $price * $quantity;

   



// Configure API key authorization: JWT

$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Authorization', $auth_token);



$apiInstance = new Swagger\Client\Api\MessagesApi(

    // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.

    // This is optional, `GuzzleHttp\Client` will be used as default.

    new GuzzleHttp\Client(),

    $config

);

$content['sender'] = 'Dustcap';

$content['destination'] = $phone;

$smsContentText = "Name: ". $name. ", " .

					"Phone: ". $phone . ", ".

					"Door: ". $door. ", ".

					"Postcode: ". $postcode. ", ".

                    "Size: ". $size. ", " .

                    "Registration: ". $registration. ", " .

					"Qty: ". $quantity. ", " .

					"Brand: ". $brand. ", ".

					"Price: £". $totalPrice. ", ".

					"Notes: ". $notes;

// $smsContentText = join(" , ", $smsContent);



$content['content'] = 'Sender: Dustcap; Tel:07875937353 - ' . $smsContentText;



$body = new \Swagger\Client\Model\Message($content);



$msg = 'Message sent to '. $phone;

try {

        $result = $apiInstance->sendMessage($body);

        

        $msg = 'Message sent to '. $phone;

        

        // Email details

        $to = 'tyreorder@dustcap.co.uk';

        $subject = 'Quote Request - Dustcap.co.uk';

        $headers = "From: $name <adminquote@dustcap.co.uk>\r\n";

        $headers .= "Content-Type: text/html\r\n";

        

        // Email body

        $message = "

            <html>

            <head>

                <title>Quote Request</title>

            </head>

            <body>

                <h2>Quote Request</h2>

                <p><strong>Name:</strong> $name</p>

                <p><strong>Phone Number:</strong> $phone</p>

                <p><strong>Door No:</strong> $door</p>

                <p><strong>Postcode:</strong> $postcode</p>

                <p><strong>Registration Number:</strong> $registration</p>

                <p><strong>Tyre Size:</strong> $size</p>

                <p><strong>Tyre Quantity:</strong> $quantity</p>

                <p><strong>Tyre Brand:</strong> $brand</p>
                <p><strong>{$lwn_label}:</strong> {$lwn_available}</p>
                <p><strong>Price:</strong> $price</p>

                <p><strong>Notes:</strong> $notes</p>

            </body>

            </html>

        ";

        

        // Send the email

        mail($to, $subject, $message, $headers);

    

    	// save quote to order database

    	// Fitter details has been assigned to a hardcoded fitter withid 5

    	// since the form doesn't have select fitter option

    

    	// save user

    	$customerId = saveUser($name, $phone, $door, $postcode);

    

    	//save quote

    		

    	$quoteId = saveQuote($customerId,'0');

    

    	//save quote details

    

    	$quoteDetailId = saveQuoteDetails($quoteId, $price,$quantity, $width, $profile, $diameter, $brand, $registration);

    

    

    	//save order

    

    	saveOrder($quoteId, $customerId, ($quantity*$price));

    

    

    	$infoDiv = '<div class="success">' . $msg . '</div>';

    	



    } catch (Exception $e) {

        $error = $data = json_decode($e->getResponseBody());

        

        $msg = 'Error sending messaage: '. $error->message;

    	$infoDiv = '<div class="error">' . $msg . '</div>';

    }

}





?>

<!DOCTYPE html>

<html>

<head>

	<meta name="viewport" content="width=device-width, initial-scale=1.0">

	<title>Dustcap Quote Form</title>

	<style>

		form {

			max-width: 100%;

			margin: 0 auto;

			padding: 20px;

			background-color: #f2f2f2;

			border-radius: 10px;

			box-shadow: 0 0 10px rgba(0,0,0,0.2);

			font-family: Arial, sans-serif;

		}



		label {

			display: block;

			margin-bottom: 5px;

			font-weight: bold;

		}



		.tyreSize {

			display: flex;
			flex-wrap: wrap;
			gap: 10px;

		}

		/* Ensure the tyre size dropdowns are responsive */
		.tyreSize select {
			width: 30%;
			min-width: 110px;
			margin-right: 10px;
		}

		@media (max-width: 600px) {
			.tyreSize { flex-direction: column; }
			.tyreSize select { width: 100%; margin-right: 0; }
		}



		input[type=text],

		input[type=number],

		input[type=phone],

		textarea {

			width: 90%;

			padding: 10px;

			border-radius: 5px;

			border: none;

			background-color: #fff;

			box-shadow: 0 0 5px rgba(0,0,0,0.2);

			font-size: 16px;

			margin-bottom: 20px;

			resize: none;

		}

		

		select {

			width: 15%;

			padding: 10px;

			margin-right: 20px;

			border-radius: 5px;

			border: none;

			background-color: #fff;

			box-shadow: 0 0 5px rgba(0,0,0,0.2);

			font-size: 16px;

			margin-bottom: 20px;

			resize: none;

		}



		button[type=submit] {

			background-color: #4CAF50;

			color: #fff;

			border: none;

			border-radius: 5px;

			padding: 10px 20px;

			cursor: pointer;

			font-size: 16px;

			transition: background-color 0.3s ease;

		}



		button[type=submit]:hover {

			background-color: #3e8e41;

		}



	.success,

	.error {

		border: 1px solid;

		margin: 10px auto;

		padding: 15px 10px 15px 50px;

		background-repeat: no-repeat;

		background-position: 10px center;

		max-width: 80%;

	}



	.error {

		color: #D8000C;

		background-color: #FFBABA;

		background-image: url('https://i.imgur.com/GnyDvKN.png');

	}

	.error:before{

		font-family: FontAwesome;

		content: '\f057';

		font-size: 24px;

		color: #D8000C;

	}

	.success {

		color: #4F8A10;

		background-color: #DFF2BF;

		background-image: url('https://i.imgur.com/Q9BGTuy.png');

	}



	.errorDiv {

		width: 60%;

		color: red;

		font-size: 12px;

		margin-bottom: 15px;

	}

	</style>

</head>

<body>

	<?php

		if(isset($msg))  {

			echo $infoDiv;

		}

	?>

	<h2>Fitting Request</h2>

	<form method="POST" action="<?=$_SERVER['PHP_SELF']?>" id="quote_form">

		<label for="name">Name:</label>

		<input type="text" id="name" name="name" placeholder="Your name..">

		<div id="nameError" class="errorDiv"></div>



		<label for="phone">Phone number:</label>

		<input type="phone" id="phone" name="phone" placeholder="Your phone number..">

		<div id="phoneError" class="errorDiv"></div>



		<label for="door">Fitting Address:</label>

		<input type="text" id="door" name="door" placeholder="Fitting Location.." >

		<div id="doorError" class="errorDiv"></div>



		<label for="postcode">Postcode:</label>

		<input type="text" id="postcode" name="postcode" placeholder="Your postcode.." >

		<div id="postcodeError" class="errorDiv"></div>

		

		<label for="registration">Registration Number:</label>

		<input type="text" id="registration" name="registration" placeholder="Your Vehicle Registration Number." >

		<div id="registrationError" class="errorDiv"></div>

		



		<label for="size">Tyre size:</label>

		<!-- <input type="text" id="size" name="size" placeholder="Your tyre size.." > -->

		<div class="tyreSize">

			<select name="width"  id="width" required>

				<option value="0">Select Tyre Width</option>

			<?php

			while ($row1 = $result1->fetch_array()) {

				print "<option value='$row1[0]' ";

				print ">$row1[0]</option>\n";

			}							      

			?>

			</select>

			<select name="profile" id="profile" >

			<option value="0">Select Tyre Profile</option>

			<?php

			while ($row2 = $result2->fetch_array()) {

				print "<option value='$row2[0]' ";

				print ">$row2[0]</option>\n";

			}							      

			?>

			</select>

			<select name="diameter" id="diameter">

			<option value="0">Select Wheel Size</option>

			<?php

			while ($row3 = $result3 -> fetch_array ()) {

				print "<option value='$row3[0]' ";

				print ">$row3[0]</option>\n";

			}							      

			?>

			</select>

			<!-- <select name="speed">

				<option value="0">Speed Rating</option>

				<option value="">All</option>

			<?php

			// while ($row4 = $result4 -> fetch_array()) {

			// 	if ($row4[0] != ""){

			// 		print "<option value='$row4[0]'".">".$row4[0]."</option>";

			// 	}

			// }							      

			?>

			</select> -->

		</div>

		<div id="sizeError" class="errorDiv"></div>



		<label for="quantity">Tyre Quantity:</label>

		<input type="number" id="quantity" name="quantity" placeholder="Your tyre quantity.." >

		<div id="quantityError" class="errorDiv"></div>



		<label for="brand">Tyre Brand:</label>

		<input type="text" id="brand" name="brand" placeholder="Your tyre brand.." >

		<div id="brandError" class="errorDiv"></div>



		<label for="price">Price Per Tyre:</label>

		<input type="text" id="price" name="price" placeholder="Price.." >

		<div id="priceError" class="errorDiv"></div>



		<label for="notes">Notes:</label>

		<textarea id="notes" name="notes" placeholder="Any additional notes.."></textarea>

		<div class="checkbox">

			<label for="locking_wheel_nut">

				<input type="checkbox" id="locking_wheel_nut" name="locking_wheel_nut" value="1"> I confirm I have my locking wheel nut available

			</label>

		</div>

		<div>

			<button type="submit" name="send" value="send">Send</button>

		</div>

	</form>

	<script type="text/javascript" src="scripts/form_validator.js"></script>

</body>

</html>



<?php

$conn->close();

?>