<?php namespace App\Controller;
use App\{Entity\OrderDetail, SpecialManager};
use DateTime;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\{Request, Response};
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use Symfony\Component\Routing\Annotation\Route;
/**
* Class DefaultController
* @package Almeda\Controller
*/
class DefaultController extends AbstractController {
#[Route('/', name: 'app_default_index')]
public function indexAction(): Response {
return $this->render( 'index.html.twig' );
}
#[Route('/history', name: 'app_default_history')]
public function historyAction(): Response {
return $this->render( 'history.html.twig' );
}
#[Route('/chocolate', name: 'app_default_chocolate')]
public function chocolateAction( ManagerRegistry $doctrine ): Response {
return $this->render( 'chocolate.html.twig', [
'chocArray' => $this->getPageData( 1, $doctrine ),
] );
}
#[Route('/nuts', name: 'app_default_nuts')]
public function nutsAction( ManagerRegistry $doctrine ): Response {
return $this->render( 'nuts.html.twig', [
'nutsArray' => $this->getPageData( 2, $doctrine ),
] );
}
public function getPageData( $category, ManagerRegistry $doctrine ): array {
$conn = $doctrine->getConnection();
$sql = "SELECT * FROM almeda.vPageSectionInfo WHERE CategoryID = :catID ";
if( $category === 1 ) {
$sql .= 'OR ProductID = 9 ';
}
$sql .= 'ORDER BY PageTitle, PageSequence, SizeSequence, ProductCost;';
$data = $conn->prepare( $sql );
$data->bindValue( 'catID', $category );
return $data->executeQuery()->fetchAllAssociative();
}
#[Route('/order', name: 'app_default_order')]
public function orderAction(ManagerRegistry $doctrine): Response {
$jscript = $this->shipToFormAction($doctrine);
$chocArray = $this->getPageData( 1, $doctrine );
$nutsArray = $this->getPageData( 2, $doctrine );
return $this->render( 'order.html.twig', [ 'js' => $jscript, 'chocArray' => $chocArray, 'nutsArray' => $nutsArray ] );
}
#[Route('/orderSubmit', name: 'app_default_ordersubmit')]
public function orderSubmitAction( Request $request, MailerInterface $mailer, ManagerRegistry $doctrine): Response {
$errorMessage = '';
$postData = $request->request->all();
$bill_name = $postData['bill_name'];
$bill_street = $postData['bill_street'];
$bill_street_2 = $postData['bill_street_2'];
$bill_city = $postData['bill_city'];
$bill_state = $postData['bill_state'];
$bill_zip = $postData['bill_zip'];
$day_phone = $postData['day_phone'];
$eve_phone = $postData['eve_phone'];
$email = $postData['email'];
$recipNums = $postData['recip_nums'];
$recipArr = explode( ',', $recipNums );
$recipCount = count( $recipArr );
$total = 0;
$ship_name_rows = [];
$ship_street_rows = [];
$ship_street_2_rows = [];
$ship_city_rows = [];
$ship_state_rows = [];
$ship_zip_rows = [];
$bus_add_rows = [];
$gift_wrap_rows = [];
$greeting_rows = [];
$greetings_to_rows = [];
$ship_now_rows = [];
$ship_later_rows = [];
$ship_month_rows = [];
$ship_year_rows = [];
$check_mo_encl_rows = [];
$orderArr2 = [];
$quantity_rows = [];
$size_rows = [];
$product_rows = [];
for ( $i = 0; $i < $recipCount; $i ++ ) {
$whichRecip = $recipArr[$i];
$ship_name_rows[] = $postData["ship_name$whichRecip"];
$ship_street_rows[] = $postData["ship_street$whichRecip"];
$ship_street_2_rows[] = $postData["ship_street_2$whichRecip"];
$ship_city_rows[] = $postData["ship_city$whichRecip"];
$ship_state_rows[] = $postData["ship_state$whichRecip"];
$ship_zip_rows[] = $postData["ship_zip$whichRecip"];
$gift_wrap_rows[] = isset( $postData["gift_wrap$whichRecip"] ) ? 'yes' : 'no';
$greeting_rows[] = isset( $postData["greeting$whichRecip"] ) ? 'yes' : 'no';
$greetings_to_rows[] = $postData["greetings_to$whichRecip"];
$bus_add_rows[] = isset( $postData["bus_add$whichRecip"] ) ? 'yes' : 'no';
$ship_now_rows[] = isset( $postData["ship_now$whichRecip"] ) ? 'yes' : 'no';
$ship_later_rows[] = isset( $postData["ship_later$whichRecip"] ) ? 'yes' : 'no';
$ship_month_rows[] = $postData["ship_month$whichRecip"];
$ship_year_rows[] = $postData["ship_year$whichRecip"];
$check_mo_encl_rows[] = isset( $postData["check_mo_encl$whichRecip"] ) ? 'yes' : 'no';
$orderNums[] = $postData["order_nums$whichRecip"];
$orderArr = explode( ',', $orderNums[$i] );
foreach ( $orderArr as $jValue ) {
$quantity_rows[$i][] = $postData["{$whichRecip}quantity$jValue"];
$product_rows[$i][] = $postData["{$whichRecip}product$jValue"];
$size_rows[$i][] = $postData["{$whichRecip}size$jValue"];
$orderArr2[$i][] = $jValue;
}
}
$notes = $postData['notes'];
$ip = getenv( 'REMOTE_ADDR' );
if ( false !== stripos( $notes . $bill_name . $bill_street . $bill_street_2 . $email . $bill_city . $day_phone . $eve_phone, 'http' ) ) {
$errorMessage .= 'We do not allow weblinks in any of the fields! ';
return $this->render( 'orderError.html.twig', compact( 'errorMessage' ) );
}
if ( ! ( str_contains($email, '@') && str_contains($email, '.')) ) {
$errorMessage .= <<<"HTML"
<h2>Use Back - Enter valid e-mail</h2>
<h2>Order was NOT submitted</h2>\n
HTML;
return $this->render( 'orderError.html.twig', compact( 'errorMessage' ) );
}
/*
if ( empty( $bill_name ) ||
empty( $email ) ||
empty( $bill_street ) ||
empty( $bill_city ) ||
empty( $bill_state ) ||
empty( $bill_zip ) ||
( empty( $day_phone ) && empty( $eve_phone ) )
) {
$errorMessage .= "<h2>Use Back - fill in billing information fields</h2>\nUse back! !";
return $this->render( 'orderError.html.twig', compact( 'errorMessage' ) );
}
*/
$name = $bill_name;
$date_now = new DateTime();
$todayis = date( 'l, F j, Y, g:i a' );
$message = <<<"HTML"
<html lang="en"><body> $todayis [EST] <br /><br />
<b>Billing Information:</b><br />
Name: $bill_name <br />
Street: $bill_street <br />
Street 2: $bill_street_2 <br />
City: $bill_city <br />
State: $bill_state <br />
Zipcode: $bill_zip <br /><br />
<b>Other Information:</b><br />
Daytime Phone: $day_phone<br />
Evening Phone: $eve_phone<br />
Email: $email <br /><br />
<b>Shipping Information:</b><br />
HTML;
$grand_total = 0;
$row_count = count( $ship_name_rows );
$i = $j = 0;
do {
$j++;
$message .= <<<"HTML"
<b>Record $j</b><br />
Name: $ship_name_rows[$i] <br />
Street: $ship_street_rows[$i] <br />
Street 2: $ship_street_2_rows[$i] <br />
City: $ship_city_rows[$i] <br />
State: $ship_state_rows[$i] <br />
Zipcode: $ship_zip_rows[$i] <br />
Business Address: $bus_add_rows[$i] <br />
HTML;
if ( $gift_wrap_rows[$i] === 'yes' && 1 === 2 ) {
$message .= "Gift Wrap: $gift_wrap_rows[$i]<br />";
}
if ( $greeting_rows[$i] === 'yes' ) {
$message .= "Greeting: $greetings_to_rows[$i]<br />";
}
if ( $ship_now_rows[$i] === 'yes' ) {
$message .= "Ship Now: $ship_now_rows[$i]";
} else if ( $ship_later_rows[$i] === 'yes' ) {
$message .= "Ship Later: $ship_later_rows[$i] ($ship_month_rows[$i] / $ship_year_rows[$i])";
} else {
$message .= "Check/MO Enclosed: $check_mo_encl_rows[$i]";
}
$order_row_count = count( $orderArr2[$i] );
$message .= <<<"HTML"
<br />
<table><thead>
<tr><th colspan='4'>Order Details</th></tr><tr>
<th>Qty</th>
<th>Product</th>
<th>Size</th>
<th>Total</th>
</tr></thead><tbody>
HTML;
$conn = $doctrine->getConnection();
for ( $j = 0; $j < $order_row_count; $j ++ ) {
$subtotal = $quantity_rows[$i][$j] * $size_rows[$i][$j];
$total += $subtotal;
$product = $product_rows[$i][$j];
$size = $size_rows[$i][$j];
$sql = 'SELECT * FROM almeda.product WHERE id = :id';
$query = $conn->prepare( $sql );
$query->bindValue( 'id', $product );
$data = $query->executeQuery()->fetchAllAssociative();
$product = htmlentities( $data[0]['title'], ENT_QUOTES );
$group = htmlentities( $data[0]['size_id'], ENT_QUOTES );
$sql = 'SELECT * FROM almeda.size WHERE product_id = :pid AND cost = :cost';
$query = $conn->prepare( $sql );
$query->execute( [ 'pid' => $group, 'cost' => $size ] );
$data2 = $query->executeQuery()->fetchAllAssociative();
$size = $data2[0]['size'] . " (\$$size)";
$subtotfmt = number_format( $subtotal, 2 );
$message .= <<<HTML
<tr>
<td style='text-align:right;'>{$quantity_rows[$i][$j]}</td>
<td style='text-align:left;'>$product</td>
<td style='text-align:right;'>$size</td>
<td style='text-align:right;'>$$subtotfmt</td>
</tr>
HTML;
}
$message .= "</tbody><tfoot><tr><th style='text-align:right;' colspan='4'>Sub-total (before shipping & applicable discounts): \$" . number_format( $total, 2 ) .
'</th></tr></tfoot></table> <br /><br />';
$grand_total += $total;
$total = 0;
$i ++;
} while ( $i < $row_count );
$message .= '<br /><b>Additional Notes:</b><br />' . $notes . '<br />Grand total for order (before shipping & applicable discounts): $' .
number_format( $grand_total, 2 ) . "<br /><input type='hidden' value='" . $ip . "' /></body></html>";
try {
$newOrder = (new OrderDetail())
->setIp($ip)
->setUserName($name)
->setEmail($email)
->setDate($date_now)
->setRecipNum($recipCount)
->setOrderTotal($grand_total)
->setMessage($message)
;
$em = $doctrine->getManager();
$em->persist($newOrder);
$em->flush();
$emailObj = (new Email())
->subject('New Order!')
->to( new Address( $email, $bill_name ) )
->cc( new Address( 'info@al-meda.com', 'Al-Meda Chocolates, Inc.' ) )
->from( new Address( $email, $bill_name ) )
->replyTo( new Address( $email, $bill_name ) )
->cc( new Address( 'almeda@rtecexpress.net', 'Al-Meda Chocolates, Inc.' ) )
// ->bcc( new Address( 'admin@manzwebdesigns.com', 'Al-Meda Webmaster' ) )
->html( $message );
$mailer->send( $emailObj );
} catch ( TransportExceptionInterface $exception ) {
$encoded_message = preg_replace( '/^$^$/', '', rawurlencode( $message ) );
$message = <<<HTML
<div class="alert alert-warning" style="font-weight: bold; font-size: 18px;">
I am sorry, but we couldn't automatically email your order.<br/>Please either call us at
<a href='tel:419-446-2676'>(419) 446-2676</a> or, if you wish to email us directly,
<a href="mailto:info@al-meda.com?subject=New Order!&body=$encoded_message">please click here</a>
to send it using your email client with your order in the email body to send.<br/>Please accept our apology.<br/><br/>Thanks.
</div>
<h3>Your order:</h3>
$message
HTML;
return $this->render( 'orderError.html.twig', array( 'message' => $message ) );
}
return $this->render( 'orderSuccess.html.twig',
array(
'message' => <<<"HTML"
Thank you, $bill_name, your order was successfully sent! Please check your email ($email) for confirmation,
we will process your order as soon as possible!<br />Please click <a href='/order'>here</a> to return to the order page
or <a href='/'>here</a> to return to the home page.<br /><br /><b>NOTE: If you don't recieve a confirmation email, please
check your spam mailbox and email the <a href='mailto:admin@manzwebdesigns.com' target='_blank'>webmaster</a>
if it isn't there!</b><br><br>Your order:<br>$message
HTML
) );
}
#[Route('/shipToForm', name: 'app_default_shiptoform')]
public function shipToFormAction(ManagerRegistry $doctrine): string {
$conn = $doctrine->getConnection();
$sql = <<<SQL
SELECT p.id
,p.title
,p.description
,c.title AS category
,p.size_id AS grp
FROM almeda.product p
JOIN almeda.category c
ON c.id = p.category_id
WHERE p.enabled = 1
ORDER BY p.size_id, p.title
SQL;
$query = $conn->query( $sql );
$data = $query->fetchAll();
$groupArray = array();
foreach ( $data as $product ) {
$groupArray[ $product['id'] ] = array( 'group_id' => $product['grp'] );
}
$sql = 'SELECT DISTINCT product_id FROM almeda.size ORDER BY product_id;';
$query = $conn->query( $sql );
$sizeIndex = $query->fetchAll();
$sql = 'SELECT * FROM almeda.size ORDER BY product_id, id;';
$query = $conn->query( $sql );
$sizeData = $query->fetchAll();
$sizeArray = array();
foreach ( $sizeIndex as $index ) {
$sizeArray[] = array(
'prod_id' => $index['product_id'],
'options' => $this->getSizeOptions( $index['product_id'], $sizeData ),
);
}
$productOptions = '';
foreach ( $data as $value ) {
$id = $value['id'];
$description = htmlentities( $value['description'], ENT_QUOTES );
$category = htmlentities( $value['category'], ENT_QUOTES );
$title = htmlentities( $value['title'], ENT_QUOTES );
$productOptions .= sprintf("<option value=\"%s\" title=\"%s (%s)\">%s</option>", $id, $description, $category, $title);
}
return $this->renderView( 'shipToForm.js.twig', [
'groupArray' => json_encode( $groupArray, JSON_THROW_ON_ERROR ),
'sizeArray' => json_encode( $sizeArray, JSON_THROW_ON_ERROR ),
'productOptions' => $productOptions,
] );
}
protected function getSizeOptions( $tmpNum, $tmpData ): string {
$tmpRetVal = '';
foreach ( $tmpData as $value ) {
$id = $value['product_id'];
if ( $id === $tmpNum ) {
$cost = htmlentities( $value['cost'], ENT_QUOTES );
$size = htmlentities( $value['size'], ENT_QUOTES );
$tmpRetVal .= sprintf( '<option value="%s" title="%s">%s ($%s)</option>', $cost, $cost, $size, $cost );
}
}
return $tmpRetVal;
}
#[Route('/specials', name: 'app_default_specials')]
public function specialsAction(): Response {
$specialMgr = new SpecialManager();
$specials = null; //$specialMgr->getCurrentSpecials();
return $this->render( 'specials.html.twig', [ 'specials' => $specials ] );
}
#[Route('/stores', name: 'app_default_stores')]
public function storesAction(): Response {
return $this->render( 'stores.html.twig' );
}
#[Route('/viewOrders', name: 'app_default_vieworders')]
public function viewOrdersAction(ManagerRegistry $doctrine): Response {
$em = $doctrine->getManager();
$orders = $em->getRepository(OrderDetail::class)
->findBy( [], ['date' => 'DESC'], 100);
return $this->render( 'viewOrders.html.twig', compact('orders') );
}
}