<?php

/**
 * This form serves you to modify the basic configuration of your installation
 */
session_start();
define("ADMIN", true);
//////////////////////////////////////////////
define("TITLE_ELEMENT", "Create company");
//////////////////////////////////////////////
require_once("../common/lib.php");
require_once("../common/setenv.php");
require_once("../api/class.restframework.php");
require_once("../api/class.saas.php");
////////////////////////////////////////////////
$_SESSION['msg_signup_success'] = null;
/////////////////////////////////////////////
$restapi = new RestFrameWork();
// only allow get method
$saas = new SaaS($restapi);
// print_r($_POST);
// print_r($_SESSION);

$countries = $saas->getAllCountries();

$db_success = false;
// $_SESSION['msg_signup_success'] = "Congratulations! You have successfully finished creating your account. Click on <a class=\"btn btn-default\" href=\"login.php\">Log in</a> to begin.<br>";
$field_notice = array();
////////////////////////////////////////////////////////////////
$request_uri = explode("/", trim($_SERVER['REQUEST_URI'], "/"));
////////////////////////////////////////////////////////////////
// try {
//     $pms_db = new db("mysql:host=" . PMS_DB_HOST . ";port=" . PMS_DB_PORT . ";dbname=" . PMS_DB_NAME . ";charset=utf8", PMS_DB_USER, PMS_DB_PASS);
// } catch (PDOException $e) {
// }
//////////////////////////////////////////////////////////////
$country = '';
$site_title = '';
$company_name = '';
$email = '';
$username = '';
$password = '';
$last_name = '';
$first_name = '';
$email = '';
$address = '';
$postcode = '';
$city = '';
$mobile = '';
$phone = '';

// if ($pms_db !== false && pms_db_table_exists($pms_db, "pm_%") === true) {
//     $installed = true;
//     $_SESSION['msg_notice'][] = "It seems that Pandao CMS is already installed. Remove your former tables from your database to reinstall it <a class=\"btn btn-default\" href=\"login.php\">Log in</a>";
// }

if (isset($_POST['create_company'])) {
    $site_title = htmlentities($_POST['site_title'], ENT_QUOTES, 'UTF-8');
    $first_name = htmlentities($_POST['first_name'], ENT_QUOTES, 'UTF-8');
    $last_name = htmlentities($_POST['last_name'], ENT_QUOTES, 'UTF-8');
    $address = htmlentities($_POST['address'], ENT_QUOTES, 'UTF-8');
    $postcode = htmlentities($_POST['postcode'], ENT_QUOTES, 'UTF-8');
    $city = htmlentities($_POST['city'], ENT_QUOTES, 'UTF-8');
    $company_name = htmlentities($_POST['company_name'], ENT_QUOTES, 'UTF-8');
    $country = htmlentities($_POST['country'], ENT_QUOTES, 'UTF-8');
    $mobile = htmlentities($_POST['mobile'], ENT_QUOTES, 'UTF-8');
    $phone = htmlentities($_POST['phone'], ENT_QUOTES, 'UTF-8');
    $email = htmlentities($_POST['email'], ENT_QUOTES, "UTF-8");
    $username = htmlentities($_POST['username'], ENT_QUOTES, "UTF-8");
    $password = $_POST['password'];
    ///////////////////////////////////////////////////////////////////////
    if ($country == '' || $country == '0') $field_notice['country'] = "Required field";

    if ($first_name == '') $field_notice['first_name'] = "Required field";
    if ($last_name == '') $field_notice['last_name'] = "Required field";
    ///////////////////////////////////////////////////////////
    if ($email == '' || preg_match('/^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$/i', $email) !== 1) $field_notice['email'] = "Required field";
    if ($username == "") $field_notice['username'] = "Required field";
    //// Test if username exists
    if (!empty($username) && $restapi->UserExists($username)) $field_notice['username'] = "Username already exists";
    ////////////////////////////////////////////
    if ($password == "") $field_notice['password'] = "Required field";
    elseif ($password != $_POST['password2']) $field_notice['password'] = "The passwords don't match";
    elseif (mb_strlen($password, "UTF-8") < 6) $field_notice['password'] = "The password is too short";
    if ($email == "" || !preg_match("/^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$/i", $email)) $field_notice['email'] = "Invalid email address";
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //// Test if email exists
    if (!empty($email) && $restapi->EmailExists($email)) $field_notice['email'] = "Email address already exists";
    ////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////
    if ($company_name == '') $field_notice['company_name'] = "Required field";
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //// Test if email exists
    if (!empty($company_name) && $saas->company->CompanyNameExists($company_name)) $field_notice['company_name'] = "Company name already taken";
    ////////////////////////////////////////////
    if ($site_title == '') $field_notice['site_title'] = "Required field";
    if ($address == '') $field_notice['address'] = "Required field";
    if ($postcode == '') $field_notice['postcode'] = "Required field";
    if ($city == '') $field_notice['city'] = "Required field";
    if ($phone == '' || preg_match('/([0-9\-\s\+\(\)\.]+)/i', $phone) !== 1) $field_notice['phone'] = "Required field";
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    if (count($field_notice) == 0) {
        $data = array(
            "site_title" => $site_title,
            "first_name" => $first_name,
            "last_name" => $last_name,
            "address" => $address,
            "postcode" => $postcode,
            "city" => $city,
            "company_name" => $company_name,
            "db_name" => "",
            "country" => $country,
            "mobile" => $mobile,
            "phone" => $phone,
            "email" => $email,
            "username" => $username,
            "password" => $password,
            "type" => "administrator",
            "checked" => true,
            "fb_id" => null,
            "is_super_user" => true,
            "is_staff" => true,
            "is_verified" => true,
            "is_active" => true,
            "token" => "",
            "add_date" => null,
            "edit_date" => null,

        );
        // create compny
        $response = $saas->createAccount($data);
        // print_r($response);
        $companyid = $response["company"]["id"];
        $company =  $saas->CreateCompany($companyid);
        // print_r($company);
        $saas->CreateUser($response, $data);
        // print_r($company);
        $_SESSION['msg_signup_success'] = "Congratulations! You have successfully finished creating your account. Click on <a class=\"btn btn-default\" href=\"login.php\">Log in</a> to begin.<br>";
    }
}
//////////////////////////////////////////////
// $csrf_token = pms_get_token("setup");
?>

<!DOCTYPE html>

<head>
    <?php
    if (!defined("PMS_ADMIN_FOLDER")) define("PMS_ADMIN_FOLDER", "admin");
    include("includes/inc_header_common.php"); ?>
    <script>
        $(function() {
            $('#db_name').bind('blur keyup', function() {
                $('#db_user').val($(this).val());
            });
            <?php foreach ($field_notice as $field => $notice) echo "$('.field-notice[rel=\"" . $field . "\"]').html('" . addslashes($notice) . "').fadeIn('slow').parent().addClass('alert alert-danger');\n"; ?>
        });
    </script>
</head>

<body class="white">
    <div class="container">
        <div class="alert-container">
            <div class="alert alert-success alert-dismissable"></div>
            <div class="alert alert-warning alert-dismissable"></div>
            <div class="alert alert-danger alert-dismissable"></div>
        </div>
        <?php if ($_SESSION['msg_signup_success'] == null) { ?>
            <h1>Welcome</h1>
            <p>Fill fields with your information. It will take only a few seconds. You can always modify these parameters later.</p>
            <form id="form" class="form-horizontal" role="form" action="signup.php" method="post">
                <fieldset>
                    <legend>Create account</legend>
                    <div class="row mb10">
                        <label class="col-lg-3 control-label">Country</label>
                        <div class="col-lg-6">
                            <select class="form-control" name="country">
                                <option value="0">-select country-</option>
                                <?php
                                foreach ($countries as $mcountry) {
                                    //////////////////////////////////////////////
                                    $idcountry = $mcountry["id"];
                                    $country_name = $mcountry["name"];
                                    $code = $mcountry["code"];
                                    //////////////////////////////////////////////
                                    $selected = ($country == $country_name) ? ' selected' : '';

                                    echo '<option value="' . $country_name . '"' . $selected . '>' . $country_name . '</option>';
                                }
                                ?>
                            </select>
                            <div class="field-notice" rel="country"></div>
                        </div>
                    </div>
                    <div class="row mb10">
                        <label class="col-md-3 control-label">First Name</label>
                        <div class="col-md-6">
                            <input type="text" class="form-control" name="first_name" value="<?php echo $first_name; ?>" />
                            <div class="field-notice" rel="first_name"></div>
                        </div>

                    </div>
                    <div class="row mb10">
                        <label class="col-md-3 control-label">Last Name</label>
                        <div class="col-md-6">
                            <input type="text" class="form-control" name="last_name" value="<?php echo $last_name; ?>" />
                            <div class="field-notice" rel="last_name"></div>
                        </div>
                    </div>
                    <div class="row mb10">
                        <label class="col-md-3 control-label">
                            E-mail
                        </label>
                        <div class="col-md-6">
                            <input class="form-control" type="text" value="<?php echo $email; ?>" name="email">
                            <div class="field-notice" rel="email"></div>
                        </div>
                    </div>
                    <div class="row mb10">
                        <label class="col-md-3 control-label">
                            Username (login name)
                        </label>
                        <div class="col-md-6">
                            <input class="form-control" type="text" value="<?php echo $username; ?>" name="username">
                            <div class="field-notice" rel="username"></div>
                        </div>
                    </div>
                    <div class="row mb10">
                        <label class="col-md-3 control-label">
                            Password
                        </label>
                        <div class="col-md-3">
                            <input class="form-control" type="password" value="<?php echo $password; ?>" name="password" placeholder="> 5 caracters">
                            <div class="field-notice" rel="password"></div>
                        </div>
                        <div class="col-md-3">
                            <input class="form-control" type="password" value="" name="password2" placeholder="Confirm password">
                        </div>
                    </div>
                </fieldset>
                <fieldset>
                    <legend>Company</legend>
                    <div class="row mb10">
                        <label class="col-md-3 control-label">
                            Company name: (Hotel Name)
                        </label>
                        <div class="col-md-6">
                            <input class="form-control" type="text" value="<?php echo $company_name; ?>" name="company_name">
                            <div class="field-notice" rel="company_name"></div>
                        </div>
                    </div>

                    <div class="row mb10">
                        <label class="col-md-3 control-label">
                            Site title
                        </label>
                        <div class="col-md-6">
                            <input class="form-control" type="text" value="<?php echo $site_title; ?>" name="site_title">
                            <div class="field-notice" rel="site_title"></div>
                        </div>
                    </div>
                    <div class="row form-group">
                        <label class="col-lg-3 control-label">Address</label>
                        <div class="col-lg-6">
                            <input type="text" class="form-control" name="address" value="<?php echo $address; ?>" />
                            <div class="field-notice" rel="address"></div>
                        </div>
                    </div>
                    <div class="row form-group">
                        <label class="col-lg-3 control-label">Postal code</label>
                        <div class="col-lg-6">
                            <input type="text" class="form-control" name="postcode" value="<?php echo $postcode; ?>" />
                            <div class="field-notice" rel="postcode"></div>
                        </div>
                    </div>
                    <div class="row form-group">
                        <label class="col-lg-3 control-label">City</label>
                        <div class="col-lg-6">
                            <input type="text" class="form-control" name="city" value="<?php echo $city; ?>" />
                            <div class="field-notice" rel="city"></div>
                        </div>
                    </div>
                    <div class="row form-group">
                        <label class="col-lg-3 control-label">Phone</label>
                        <div class="col-lg-6">
                            <input type="text" class="form-control" name="phone" value="<?php echo $phone; ?>" />
                            <div class="field-notice" rel="phone"></div>
                        </div>
                    </div>
                    <div class="row form-group">
                        <label class="col-lg-3 control-label">Mobile</label>
                        <div class="col-lg-6">
                            <input type="text" class="form-control" name="mobile" value="<?php echo $mobile; ?>" />
                            <div class="field-notice" rel="mobile"></div>
                        </div>
                    </div>
                </fieldset>
                <div class="row mb10">
                    <div class="col-md-9 text-right">
                        <button type="submit" name="create_company" class="btn btn-default mt15">
                            Create company
                        </button>
                    </div>
                </div>
            </form>
        <?php } else { ?>
            <div class="alert alert-success alert-dismissable">
                <?php echo $_SESSION['msg_signup_success']; ?>
            </div>
        <?php } ?>
    </div>
</body>

</html>
<?php
$_SESSION['msg_error'] = array();
$_SESSION['msg_notice'] = array();
$_SESSION['msg_signup_success'] = null;
?>