<?php

namespace Drupal\restaurant_bookings\Form\Ajax;

use Drupal\restaurant_bookings\Form;
//use Drupal\restaurant\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\restaurant\Form\AppForm;
use Drupal\restaurant\Bookings\Booking;
use Symfony\Component\HttpFoundation\Session\Session;
use Drupal\restaurant\Form\MultipartForm;

use Drupal\restaurant_bookings\Form\FormElements;
use Drupal\restaurant\Form\Heading;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require_once get_restaurant_path(true) . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'PHPMailer' . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'PHPMailer.php';
require_once get_restaurant_path(true) . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'PHPMailer' . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'SMTP.php';
require_once get_restaurant_path(true) . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'PHPMailer' . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'Exception.php';


/**
* BOOKINGS FORM STEP 1
*/
class Book extends AppForm
{
  /**
   * Returns a unique string identifying the form.
   *
   * The returned ID should be a unique string that can be a valid PHP function
   * name, since it's used in hook implementation names such as
   * hook_form_FORM_ID_alter().
   *
   * @return string
   *   The unique string identifying the form.
   */
  public function getFormId() {
    return 'booking_page';
  }

  public function buildForm(array $form, FormStateInterface $form_state)
  {

    if ($this->getSetting('requirelogin')) {

      if (! \Drupal::currentUser()->isAuthenticated()) {
        $this->addMessage($this->t('Login required to make a booking'), 'error')->http_redirect('/user/login');
      }
    }
	
    $session = $this->getSession();

    $details = $session->get('details');

    $data = $details['requirements'];
    $requirements = $session->get('checkrequirements');
    $req = array();
    foreach ($requirements as $key => $val) {
        $req[] = $key;
    }
    unset ($requirements);

    $remove = array('form_build_id', 'form_token', 'form_id', 'op', 'emailconfirmation');
    foreach ($remove as $val) {
        if (isset ($details[$val])) {
            unset ($details[$val]);
        }
    }

    $details['guests'] = $session->get('guests');
    $details['bookingtime'] = date('Y-m-d H:i:s', $this->getParam('timestamp'));

    $booking = new Booking($this->conn);

    $bookingid = $booking->makeBooking($details, $req);

    $row = $this->conn->query("SELECT * FROM restaurant_bookings WHERE id = ?", array($bookingid))->fetch();

    $sendmail = true;

    $config = \Drupal::config('system.site');
    $sitename = $config->get('name');
    $site_email = $config->get('mail');

    $smtpHost = $this->getSetting('SMTPHost');
    $sendmail = (empty ($smtpHost)) ? false : true;

    $username = $this->service->getSetting('SMTPUsername');
    $sendmail = (empty ($username)) ? false : true;

    $password = '';
    switch ($_SERVER['SERVER_NAME']) {

      case 'stage.acewebdevelopment.com.au':
      case 'restauranthq.acewebdevelopment.com.au':
      case 'restauranthq.local':
      case 'localhost':
        $password = trim(file_get_contents(get_restaurant_path(). '/devel.txt'));

      break;

      default:
        $password = $this->service->getSetting('SMTPPassword');
    }

    $sendmail = (empty ($password)) ? false : true;

    if ($sendmail) {


      $mailer = new PHPMailer(true);
      $mailer->Username = $username;
      $mailer->Password = $password;
      $mailer->setFrom($site_email, $sitename);
      $mailer->isSMTP();
      $mailer->isHTML(true);
      $mailer->SMTPDebug  = 0;
      $mailer->SMTPAuth   = true;
      $mailer->Host = $this->service->getSetting('SMTPHost');
      $protocol = $this->service->getSetting('SMTPSecure');
      if (( $protocol == 'ssl') || ($protocol == 'tls')) {
      		$mailer->SMTPOptions = array(
    				'ssl' => array(
        				'verify_peer' => false,
        				'verify_peer_name' => false,
        				'allow_self_signed' => true
    				)
    			);
      	}
      	$results  = $booking->getBookingResults($bookingid);
        $mailer->addAddress($details['email'], $details['firstname']);
        $mailer->Subject = 'Booking confirmation from ' . $sitename;
        $mailer->Body = $results->getHtmlEmail();
        $mailer->AltBody = $results->getTextEmail();

        try {
          $mailer->send();
          $error = false;
        } catch (Exception $e) {
          $error = true;
          $this->addMessage('An error occured in sending your email. Please contact the system administrator for details <p style="color: red">' . $e->getMessage() . '</p>', "error");
        }
    }
    if ($error) {
      $message = '<p>Thank you for your booking on ' . date('D, j M Y h:i', $this->getParam('timestamp')) . '. A confirmation email will be sent to you shortly confirming your reservation details.</p>';
    } else {
      $message = '<p>Thank you for your booking on ' . date('D, j M Y h:i', $this->getParam('timestamp')) . '</p>';
    }

    $form['markup'] = array(
        '#type' => 'markup',
        '#markup' => $message
      );


    return $form;

  }

  public function submitForm(array &$form, FormStateInterface $form_state) {}

}
