<?php

declare(strict_types=1);

error_reporting(E_ALL);
ini_set('display_errors', '1');

use ColemanProjects\Taxi\BookingForm;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;

require_once __DIR__ . '/vendor/autoload.php';

date_default_timezone_set('Europe/London');

$request = Request::createFromGlobals();

$template = new Twig\Environment(
    new \Twig\Loader\FilesystemLoader(__DIR__ . '/templates'),
    [
        'cache' => false,
        'strict_variables' => true
    ]
);
$template->addExtension(new \Twig\Extra\Intl\IntlExtension());

$host = $request->server->get('HTTP_HOST', '');
$path = parse_url($request->server->get('REQUEST_URI', ''), PHP_URL_PATH);

if (!($path === '/booking/' || $path === '/quotation/')) {
    die('Invalid configuration: path must be /booking/ or /quotation/');
}

$config = [];
$config['outward_journey'] = true; // all journeys have an outward part
$config['test'] = $request->query->getBoolean('test', false);
$config['booking'] = $path === '/booking/';
$config['billing'] = $config['booking'];
$config['website'] = 'Unknown'; // all forms have a website name
$config['quotation_redirect'] = ''; // all forms have a quotation redirect link
$config['css_file'] = ''; // all forms have a CSS file
$config['contact_company_name'] = false; // most forms do not have a contact company name
$config['passengers'] = true; // most journeys have a passenger count
$config['luggage'] = false; // most journeys do not have luggage
$config['taxis'] = false; // most journeys do not have a number of taxis
$config['outward_drop_off'] = true; // most journeys have an outward drop-off
$config['return_journey'] = false; // most journeys do not have a return
$config['tour'] = false; // most journeys do not have a tour
$config['guests'] = false; // most journeys do not have a guest count
$config['marshals'] = false; // most journeys do not have a marshal count
$config['taxi_model'] = false; // most journeys do not have a specified taxi model
$config['booking_duration'] = false; // most journeys do not have a booking duration
$config['wedding_taxi'] = false; // most journeys do not have a wedding taxi
$config['event'] = false; // most journeys are not an event
$config['deposit'] = '5.00'; // most journeys have a £5 deposit
$config['common_addresses'] = false; // most forms do not have a list of common addresses
$config['flight_details'] = false; // most forms do not request flight details
$config['booking_duration_options'] = [
    '1' => '1 hour',
    '2' => '2 hours',
    '3' => '3 hours',
    '4' => '4 hours',
    '5' => '5 hours',
    '6' => '6 hours',
    '7' => '7 hours',
    '8' => '8 hours',
    '24' => 'Whole Day'
];

switch ($host) {
    case 'www.londonblacktaxis.net':
    case 'londonblacktaxis.net':
    case 'londonblacktaxis.localhost':
    case 'londonblacktaxis.phpdeveloper.org.uk':
        $config['website'] = 'London Black Taxis';
        $config['email_name'] = 'London Black Taxis';
        $config['quotation_redirect'] = 'https://www.londonblacktaxis.net/thank-you-quotation/';
        $config['css_file'] = 'london-black-taxis';
        $config['return_journey'] = true;
        $config['luggage'] = true;
        $config['taxis'] = true;
        $config['common_addresses'] = true;
        $config['flight_details'] = true;
        $config['EMAIL_FROM'] = 'mike@londonblacktaxis.net';
        break;
    case 'www.londonblacktaxitours.net':
    case 'londonblacktaxitours.net':
    case 'londonblacktaxitours.localhost':
        $config['website'] = 'London Black Taxi Tours';
        $config['email_name'] = 'London Taxi Tours';
        $config['quotation_redirect'] = 'https://www.londonblacktaxitours.net/thank-you-quotation/';
        $config['css_file'] = 'london-black-taxi-tours';
        $config['tour'] = true;
        $config['EMAIL_FROM'] = 'mike@londonblacktaxitours.net';
        $config['deposit'] = '25.00';
        $config['common_addresses'] = true;
        $config['flight_details'] = true;
        break;
    case 'www.londontaximarshals.com':
    case 'londontaximarshals.com':
    case 'londontaximarshals.localhost':
        $config['website'] = 'London Taxi Marshals';
        $config['email_name'] = 'London Taxi Marshals';
        $config['quotation_redirect'] = 'https://www.londontaximarshals.com/thank-you-quotation/';
        $config['css_file'] = 'london-taxi-marshals';
        $config['contact_company_name'] = true;
        $config['passengers'] = false;
        $config['guests'] = true;
        $config['marshals'] = true;
        $config['booking_duration'] = true;
        $config['booking_duration_options'] = [
            '2' => '2 hours',
            '3' => '3 hours',
            '4' => '4 hours',
            '5' => '5 hours',
            '6' => '6 hours',
            '7' => '7 hours',
            '8' => '8 hours',
            '24' => 'Whole Day'
        ];
        $config['outward_drop_off'] = false;
        $config['event'] = true;
        $config['EMAIL_FROM'] = 'mike@londontaximarshals.com';
        break;
    case 'www.londontaxisfilmproduction.com':
    case 'londontaxisfilmproduction.com':
    case 'londontaxisfilmproduction.localhost':
        $config['website'] = 'London Taxis Film Production';
        $config['email_name'] = 'London Taxi Film Production';
        $config['quotation_redirect'] = 'https://www.londontaxisfilmproduction.com/thank-you-quotation/';
        $config['css_file'] = 'london-taxis-film-production';
        $config['contact_company_name'] = true;
        $config['taxi_model'] = true;
        $config['booking_duration'] = true;
        $config['EMAIL_FROM'] = 'mike@londontaxisfilmproduction.com';
        break;
    case 'www.londonweddingtaxis.net':
    case 'londonweddingtaxis.net':
    case 'londonweddingtaxis.localhost':
        $config['website'] = 'London Wedding Taxis';
        $config['email_name'] = 'London Taxi Weddings';
        $config['quotation_redirect'] = 'https://www.londonweddingtaxis.net/thank-you-quotation/';
        $config['css_file'] = 'london-wedding-taxis';
        $config['booking_duration'] = true;
        $config['wedding_taxi'] = true;
        $config['taxis'] = true;
        $config['EMAIL_FROM'] = 'mike@londonweddingtaxis.net';
        break;
    default:
        die('Invalid hostname');
}

$config['database'] = [
    'username' => '',
    'password' => '',
    'hostname' => 'localhost',
    'dbname' => ''
];

switch ($host) {
    case 'www.londonblacktaxis.net':
    case 'londonblacktaxis.net':
        $config['database']['username'] = 'londonbl_wrdp4';
        $config['database']['password'] = ']rRR=azkOoWf';
        $config['database']['dbname'] = 'londonbl_wrdp4';
        break;
    case 'www.londonblacktaxitours.net':
    case 'londonblacktaxitours.net':
        $config['database']['username'] = 'lonbtt26_wrdp1';
        $config['database']['password'] = '2R6fxgP4HMzT';
        $config['database']['dbname'] = 'lonbtt26_wrdp1';
        break;
    case 'www.londontaximarshals.com':
    case 'londontaximarshals.com':
        $config['database']['username'] = 'lontmar7_wrdp1';
        $config['database']['password'] = 'tYUc5{bQyrV9';
        $config['database']['dbname'] = 'lontmar7_wrdp1';
        break;
    case 'www.londontaxisfilmproduction.com':
    case 'londontaxisfilmproduction.com':
        $config['database']['username'] = 'londonfi_wrdp1';
        $config['database']['password'] = '18xjMno8huZv';
        $config['database']['dbname'] = 'londonfi_wrdp1';
        break;
    case 'www.londonweddingtaxis.net':
    case 'londonweddingtaxis.net':
        $config['database']['username'] = 'wedtax_wrdp1';
        $config['database']['password'] = 'w4BEg0QU9cUB';
        $config['database']['dbname'] = 'wedtax_wrdp1';
        break;
    case 'londonblacktaxis.phpdeveloper.org.uk':
        $config['database']['username'] = 'londonblacktaxis_phpdev';
        $config['database']['password'] = 'w4BEg0QU9cUB';
        $config['database']['dbname'] = 'londonblacktaxis_phpdev';
        break;
        break;
    case 'londonblacktaxis.localhost':
    case 'londonblacktaxitours.localhost':
    case 'londontaximarshals.localhost':
    case 'londontaxisfilmproduction.localhost':
    case 'londonweddingtaxis.localhost':
        $config['database']['username'] = 'taxi_booking';
        $config['database']['password'] = 'taxi_booking';
        $config['database']['hostname'] = 'database';
        $config['database']['dbname'] = 'taxi_booking';
        break;
}

// Always enable testing on localhost
if (stristr($host, 'localhost') !== false) {
    $config['test'] = true;
}

$bookingForm = new BookingForm($request, $config);
$today = new DateTimeImmutable();
$form = [];
$errors = [];

if ($request->getMethod() === 'POST') {
    // Always enable testing on localhost
    if (stristr($host, 'localhost') !== false) {
        $config['test'] = true;
    } else {
        $config['test'] = $request->request->getBoolean('test', false);
    }

    $form = $bookingForm->getFormPopulated();
    $errors = $bookingForm->validate();

    $redirectUriPrefix = "https://{$host}{$path}";

    if (count($errors) === 0) {
        // Always send email
        $bookingForm->sendEmail($template);

        // If booking, redirect to payment page
        if ($config['booking']) {
            $paymentUrl = $bookingForm->getPaymentUrl($redirectUriPrefix);

            if ($paymentUrl !== null) {
                $response = new RedirectResponse($paymentUrl);
                $response->send();
            } else {
                /** @todo Send email for payment redirect failure */
                $response = new RedirectResponse($redirectUriPrefix . 'failed.php');
                $response->send();
            }
        } else {
            $response = new RedirectResponse($config['quotation_redirect']);
            $response->send();
        }
    } else {
        $form['captcha_question_parts'] = explode(',', $form['captcha_question']);
    }
} else {
    $form['captcha_question_parts'] = $bookingForm->getCaptchaQuestion();
    $form['captcha_question'] = implode(',', $form['captcha_question_parts']);
}

$commonAddresses = $bookingForm->getCommonAddresses();

$template->display('index.html', [
    'config' => $config,
    'form' => $form,
    'errors' => $errors,
    'tourOptions' => $bookingForm->getTourOptions(),
    'taxiModelOptions' => $bookingForm->getTaxiModelOptions(),
    'weddingTaxiModelOptions' => $bookingForm->getWeddingTaxiModelOptions(),
    'bookingDurationOptions' => $bookingForm->getBookingDurationOptions(),
    'howFindUsOptions' => $bookingForm->getHowFindUsOptions(),
    'countryOptions' => $bookingForm->getCountryOptions(),
    'stateOptions' => $bookingForm->getStateOptions(),
    'today' => $today,
    'commonAddresses' => $commonAddresses,
    'commonAddressesJson' => json_encode($commonAddresses)
]);
