<?php

require("vendor/phpmailer/phpmailer/class.phpmailer.php");
require("vendor/phpmailer/phpmailer/class.smtp.php"); 
require('config.php');

function generate_hash()
{
 $current_date = new DateTime();
        $hash = bin2hex(random_bytes(16));
        
        $hashnew = md5($current_date->format("Y-m-d H:i:s.v")).$hash;
    return $hashnew; 
    
}

$linkID = new PDO('mysql:host='.Config::DB_HOST.';dbname='.Config::DB_NAME, Config::DB_USERNAME, Config::DB_PASSWORD);
$linkID->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Setting ERRMODE


$company_name = $linkID->query("SELECT * FROM ea_settings WHERE ea_settings.id=14")->fetchAll(PDO::FETCH_ASSOC);
$company_email = $linkID->query("SELECT * FROM ea_settings WHERE ea_settings.id=15")->fetchAll(PDO::FETCH_ASSOC);
$company_link = $linkID->query("SELECT * FROM ea_settings WHERE ea_settings.id=16")->fetchAll(PDO::FETCH_ASSOC);

$waitlistfirstname = $_POST['waitlist-firstname']; 
$waitlistlastname = $_POST['waitlist-lastname']; 
$waitlistphonenumber = $_POST['waitlist-phonenumber']; 
$waitlistemail = $_POST['waitlist-email']; 
$waitlistnotes = $_POST['waitlist-notes']; 
$waitlistservice = $_POST['waitlist-service'];
$birthdate = $_POST['waitlist-birthdate'];

$servicewhich = $linkID->query("SELECT * FROM ea_services WHERE ea_services.id=".$waitlistservice)->fetchAll(PDO::FETCH_ASSOC);
//echo $servicewhich[0]['name'];

if($servicewhich[0]['minimummaxonoff'] == 'ON') {
    $dob = new DateTime($birthdate);

    $now = new DateTime();

    $difference = $now->diff($dob);

    $age = $difference->y;

    if ($age > $servicewhich[0]['minimum'] && $age < $servicewhich[0]['maximum']) {

    }else{
        echo 'Error  - you do not have the accepted age range';
        die();
    }
}

$data = [
    'firstname' => $waitlistfirstname,
    'lastname' => $waitlistlastname,
    'phonenumber' => $waitlistphonenumber,
    'email' => $waitlistemail,
    'birthdate' => $birthdate,
    'notes'=> $waitlistnotes, 
    'service'=> $waitlistservice, 
    'hash'=> generate_hash(),
];



$sql = "INSERT INTO waitlist (firstname, lastname, phonenumber, email, birthdate, notes, pharmacynotes, service, status, date_sent, date_expires, hash) VALUES (:firstname, :lastname, :phonenumber, :email, :birthdate, :notes, ' ', :service, ' ', null, null, :hash)";
//echo $sql; 
$stmt= $linkID->prepare($sql);
$stmt->execute($data);


echo 'Your record has been successfully added to the waitlist! You will be notified by email once more appointment spots open up. If you are not able to find an appointment after receiving your email, you will be asked to put yourself back on the waitlist and we will notify you once we receive more inventory.'




?>