<?
//error_reporting(E_ALL);
//ini_set('display_errors', 1);
require('class/loadall.php');
require('../../vendor/autoload.php');
$Page = new Reg();
$HTML = new HTML($Page->DB);

if (isset($_SERVER['DBSTEVE']) && $_SERVER['DBSTEVE'] == '1') PC::debug($_POST, "top post");

$Page->changeDatabase("groupaudit");
$arr=array(
    'postdata'=>json_encode($_POST),
    'remoteserver'=>$_SERVER['REMOTE_ADDR']
);
$Page->insertSQL("incoming",$arr);
$Page->changeDatabase("group2014");

unset($_POST['failedcc']);
// find online link
$query = "SELECT onlineLink FROM online
	LEFT OUTER JOIN groups ON groups.id=online.group_id
	LEFT OUTER JOIN trips ON trips.group_id=groups.id
	WHERE trips.id=?";
$q = $Page->DB->prepare($query);
unset($var);//vars
$var[0] = $_POST['trip_id'];
try {
    $q->execute($var);
} catch (PDOException $E) {
    if (isset($_SERVER['DBSTEVE']) && $_SERVER['DBSTEVE'] == '1') {
        if (function_exists(flog)) flog($E->getMessage());
    }
}
$i = $q->fetch(PDO::FETCH_ASSOC);
$t = $Page->tripDetails($_POST['trip_id'], $i['onlineLink']);
$trip = $t['trip'];
$group = $t['group'];
$online = $t['online'];

// how many are we registering?

$pax = $_POST['pendingID'];
unset($_POST['pendingID']);

$acts = $_POST['activity'];
unset($_POST['activity']);

$subacts=$_POST['subAct'];
unset($_POST['subAct']);

foreach ($subacts as $ggidd=>$subact) {
    if($subact) $acts[$subact][$ggidd]=1;
}
$oa2 = $_POST['oa2'];
$oa3 = $_POST['oa3'];
unset($_POST['oa2']);
unset($_POST['oa3']);
if($_POST['alertEmail']) {
    foreach ($_POST['alertEmail'] as $ggiidd=>$ggitem) {
        if($ggitem) $_POST['onsiteAlert'][$ggiidd]=$ggitem;
    }
    unset($_POST['alertEmail']);
}

$bd = $_POST['birthDay'];
$bm = $_POST['birthMonth'];
$by = $_POST['birthYear'];
unset($_POST['birthDay']);
unset($_POST['birthMonth']);
unset($_POST['birthYear']);

$_POST['pretsa'] = $_POST['tsaprecheck'];
unset($_POST['tsaprecheck']);
$_POST['freqflier'] = $_POST['ffnumber'];
unset($_POST['ffnumber']);

$emergency = $_POST['em'];
unset($_POST['em']);

foreach ($emergency as $field => $item) {
    foreach ($item as $paxNumber => $v) {
        $injectEmergency[$paxNumber][$field] = $v;
    }
}


// has to do with online charges
if ($_POST['disable_cc'] == 2 && $_POST['paymentType'] == 'cc') {
    $wasDeleted = 2;
    $initialDepositTimer = time();
} else {
    $wasDeleted = NULL;
    $initialDepositTimer = NULL;
}
unset($_POST['disable_cc']);

$paymentType = $_POST['paymentType'] == 'cc' ? 1 : NULL;
unset($_POST['paymentType']);


$leadGuest = null;
foreach ($pax as $paxNumber) {
    $pend = $Page->returnOneData("guestPending", $paxNumber);
    $loop[$paxNumber]['guest_first_name'] = $pend['firstname'];
    $loop[$paxNumber]['guest_last_name'] = $pend['lastname'];
    $loop[$paxNumber]['guest_email'] = $pend['email'];
    $loop[$paxNumber]['guest_password'] = $Page->generateRandomString(8);
    $loop[$paxNumber]['guest_usingcc'] = $paymentType;
    $loop[$paxNumber]['initialDepositTimer'] = $initialDepositTimer;
    $loop[$paxNumber]['wasDeleted'] = $wasDeleted;
    if ($pend['isPrimary']) {
        $loop[$paxNumber]['guest_lead_guest'] = null;
        $leadGuest = $paxNumber;
    }
    if ($_POST['guest_lead_guest']) {
        $loop[$paxNumber]['guest_lead_guest'] = $_POST['guest_lead_guest'];
        unset($_POST['guest_lead_guest']);
        $leadGuest = $paxNumber;
    }
    if (!$pend['isPrimary']) $loop[$paxNumber]['guest_lead_guest'] = $paxNumber;
    // handle text alerts
    if ($oa2[$paxNumber] && $oa3[$paxNumber]) $loop[$paxNumber]['onsiteAlert'] = "+1" . $oa2[$paxNumber] . $oa3[$paxNumber];
    // handle birthdays
    if ($bd[$paxNumber] && $bm[$paxNumber] && $by[$paxNumber]) $loop[$paxNumber]['guest_birthday'] = $by[$paxNumber] . "-" . $bm[$paxNumber] . "-" . $bd[$paxNumber];

    if ($_POST['opt'][$paxNumber]) {
        $opts = $_POST['opt'][$paxNumber];
        unset($_POST['opt'][$paxNumber]);
        foreach ($opts as $opt => $v) {
            $_POST['gopt' . $opt][$paxNumber] = $v;
        }
    }
    unset($_POST['opt'][$paxNumber]);

    foreach ($acts as $actID => $item) {
        if ($item[$paxNumber] == 1) $injectActivities[$paxNumber][$actID] = $actID;
    }


    $injectDeposits[$paxNumber] = $_POST['payAmount'][$paxNumber];
    unset($_POST['payAmount'][$paxNumber]);

    $injectDepositsDates[$paxNumber] = $_POST['pay'][$paxNumber];
    unset($_POST['pay'][$paxNumber]);


    foreach ($_POST as $key => $item) {
        if (is_array($item)) {
            if ($item[$paxNumber]) $loop[$paxNumber][$key] = $item[$paxNumber];
        } else {
            if ($item) $loop[$paxNumber][$key] = $item;
        }
    }
    // single supp
    $splitSS = explode("single", $loop[$paxNumber]['guest_pillow']);

    if (count($splitSS) == 2) {
        $loop[$paxNumber]['guest_pillow'] = $splitSS[0];
        $loop[$paxNumber]['singleSupp'] = 1;
    }


}

// message and block if trip is full
if ($online['maxGuests']) {
    $groupID = $trip['group_id'];

    $sql = "SELECT count(guests.id) AS cnt
FROM guests
LEFT OUTER JOIN trips ON trips.id = guests.trip_id
LEFT OUTER JOIN groups ON groups.id = trips.group_id
LEFT OUTER JOIN online ON online.group_id = groups.id
WHERE online.onlineLink=?
AND guests.wasDeleted IS NULL";
    $q = $Page->DB->prepare($sql);
    unset($var); //vars
    $var[0] = $online['onlineLink'];
    $q->execute($var);
    $findRegistered = $q->fetch(PDO::FETCH_ASSOC);

    if ($findRegistered['cnt'] >= $online['maxGuests']) {
        echo "soldout";
        exit;
        //$registeredGuests = $findRegistered['cnt'];
    }

    $slackLowInventory = null;
    if (($online['maxGuests'] - $findRegistered['cnt']) < 4) {
        $slackLowInventory = "Only " . ($online['maxGuests'] - $findRegistered['cnt'] - 1) . " spot(s) remaining.";
    }
}


$gid[$leadGuest] = $Page->insertSQL("guests", $loop[$leadGuest], true);
$leadGuestPW = $loop[$leadGuest]['guest_password'];
$gidPW[$leadGuest] = $loop[$leadGuest]['guest_password'];

if ($loop[$leadGuest]['guest_insurance']) {
    $Page->updateSQL("guests", "insuranceCoverage", $loop[$leadGuest]['guest_insurance'], "id", $gid[$leadGuest]);
    $Page->updateSQL("guests", "guest_insurance", 1, "id", $gid[$leadGuest]);

    $in = json_encode($loop[$leadGuest]);
    $Page->updateSQL("guests", "insuredArray", $in, "id", $gid[$leadGuest]);
}

// credit cc on epic/ikon
if($loop[$leadGuest]['guest_usingcc']) {
    $lif=$Page->returnOneData("lifts",$loop[$leadGuest]['guest_lift']);
    if($lif['epicikon']&&$group['ccfee']) {
        $gcc=(100-($group['ccfee']))/100;
        $di=$lif['lift_priceadjustment_gross']*($group['ccfee']/100)*-1*$gcc;
        $arr=array(
            'trip_id'=>$trip['id'],
            'guest_id'=>$gid[$leadGuest],
            'deviation_title'=>'Lift pass credit card adjustment',
            'deviate_priceadjustment'=>number_format($di,2,".","")
        );
        $Page->insertSQL("deviations",$arr);
    }
}

unset($loop[$leadGuest]);

foreach ($loop as $loopID => $item) {
    $gid[$loopID] = $Page->insertSQL("guests", $item, true);
    $gidPW[$loopID] = $item['guest_password'];
    $Page->updateSQL("guests", "guest_lead_guest", $gid[$leadGuest], "id", $gid[$loopID]);
    if ($item['guest_insurance']) {
        $Page->updateSQL("guests", "insuranceCoverage", $item['guest_insurance'], "id", $gid[$loopID]);
        $Page->updateSQL("guests", "guest_insurance", 1, "id", $gid[$leadGuest]);

        $in = json_encode($item);
        $Page->updateSQL("guests", "insuredArray", $in, "id", $gid[$loopID]);
    }


    // credit cc on epic/ikon
    if($item['guest_usingcc']) {
        $lif=$Page->returnOneData("lifts",$item['guest_lift']);
        if($lif['epicikon']&&$group['ccfee']) {
            $di=$lif['depositAdjust']*($group['ccfee']/100)*-1;
            $arr=array(
                'trip_id'=>$trip['id'],
                'guest_id'=>$gid[$loopID],
                'deviation_title'=>'Lift pass credit card adjustment',
                'deviate_priceadjustment'=>number_format($di,2,".","")
            );
            $Page->insertSQL("deviations",$arr);
        }
    }

}


foreach ($injectActivities as $pax => $acts) {
    foreach ($acts as $act) {
        $arr = array(
            'guest_id' => $gid[$pax],
            'activity_id' => $act
        );
        $Page->insertSQL("activity_attending", $arr);
    }
}
foreach ($injectEmergency as $pax => $em) {
    $em['guestid'] = $gid[$pax];
    $Page->insertSQL("guestMedical", $em);
}

foreach ($injectDeposits as $pax => $dep) {
    foreach ($dep as $depNumber => $de) {
        $arr = array(
            'guest_id' => $gid[$pax],
            'payDate' => $injectDepositsDates[$pax][$depNumber],
            'payAmount' => $de,
            'payID' => md5(uniqid())
        );
        $Page->insertSQL("guestPayment", $arr);
    }
}


$clubtext = $t['clubtext'];
$Page->loadComposer($Page->composer);

/*:	hanlde an override amout   :*/
if ($trip['percentOverride']) {
    $percent = 1 + $trip['percentOverride'] / 100;
} else {
    $percent = 1;
}

// init audits
foreach ($gid as $item) {
    $Page->initialAudits($item);
}
//exit;

//  $profile = "/guest/".$p['trip_id']."/".$p['guest_password'];



if ($gid) {


    if ($online['slackNotice']) {

        $mess = "New Registration: *" . $trip['trip_name'];
        if ($group['group_destination']) $mess .= " (" . $group['group_destination'] . ")";
        $mess .= "\n";

        foreach ($gid as $item) {
            $d=$Page->returnOneData("guests",$item);
            $mess .= "> Guest Name: " . $d['guest_last_name'] . ", " . $d['guest_first_name'] . "\n";
        }
        //$mess .= "> Guest Name: " . $_POST['guest_last_name'] . ", " . $_POST['guest_first_name'] . "";
        $us=$Page->returnOneData("users",$trip['trip_sat_admin']);

        $Page->sendSlack(
            $mess,
            $us['slackid'],
            "Group Reg Bot",
            null,
            null,
            "exclamation");

//        $Page->sendSlack(
//            $mess,
//            "#9_notices",
//            "Group Reg Bot",
//            $group['group_sat_admin'],
//            null,
//            "exclamation");
    }


    if ($slackLowInventory && 0) {

        $mess = "Almost Sold Out!: *" . $trip['trip_name'];
        if ($group['group_destination']) $mess .= " (" . $group['group_destination'] . ")";
        $mess .= "* \n";
        $mess .= "> " . $slackLowInventory . "*";

        $Page->sendSlack(
            $mess,
            "#9_notices",
            "Low Inventory Bot",
            $group['group_sat_admin'],
            null,
            "warning");
    }


}





/*--------------------------------------
	generate and send email
--------------------------------------*/



$body='<style type="text/css">
        div.explain {
            margin-left :25px;
            font-style:italic;
        }
        label {
            margin-left :20px;
        }
        label.label-success {
            color: green;
        }
        label.label-important {
            color: red;
        }
    </style>';
$body .= "
***** This is an automated email, please do not reply to it *****<br><br>
We have received your online trip registration.<br><br>";
$body .= "<b>Total guests registered: " . count($gid) . "</b><br><br>";

$lg = $Page->returnOneData("guests", $gid[$leadGuest]);
$profile = "https://www.sportsamerica.com/guest/" . $lg['trip_id'] . "/" . $lg['guest_password'];
$url = "../guest/" . $lg['trip_id'] . "/" . $lg['guest_password'];

if ($lg['wasDeleted'] == 2 && $lg['guest_usingcc']) {
    $body .= "
** Please Note: An initial deposit is required to secure your reservation. If this payment is not recorded in 30 minutes your registration may be removed from the trip.
<br><br>";
}

$body .= "Trip: ";
if ($group['group_name']) $body .= $group['group_name'] . " - ";
$body .= "" . $trip['trip_name'] . "<br>
Destination: " . $group['group_destination'] . "<br>
Dates:  " . date("M j", strtotime($trip['trip_date_start'])) . " to " . date("M j, Y", strtotime($trip['trip_date_end'])) . "<br>";
if($guest['insuranceCoverage']>0) $body.="Accepted: Travel insurance protection.<br>
";
foreach ($gid as $uid) {
    $guest = $Page->returnOneData("guests", $uid);
    $thePrice = $Page->outputPrice($guest['guest_password'], $group, $percent);
    $deposits = $Page->findDeposits($uid);
    $depTable = '';
    if (count($deposits)) {
        $depTable = '<b>Deposit Schedule</b>
        <table><tr>
            <td>Date</td>
            <td></td>
            <td>Amount</td>
            </tr>';
        foreach ($deposits as $data) {
            if ($data['payAmount'] == 0) $data['payAmount'] = 'FINAL PAYMENT';
            $depTable .= '<tr><td>' . date("n/j/Y", strtotime($data['payDate'])) . '</td><td>&nbsp;&nbsp;&nbsp;</td><td>' . $data['payAmount'] . '</td></tr>';
        }
        $depTable .= '</table>';
    }

    $body .= "<h3>" . $guest['guest_first_name'] . " " . $guest['guest_last_name'] . "'s Trip Profile Page</h3>
<div style='color: red; font-weight:bold;'>Please do NOT share this link with others. This randomized URL allows you to edit parts of your trip selection and should be kept to yourself. Think of this web page URL as a password.</div>
<a href='http://www.sportsamerica.com/guest/" . $trip['id'] . "/" . $guest['guest_password'] . "'>Trip Profile Page</a><br>(http://www.sportsamerica.com/guest/" . $trip['id'] . "/" . $guest['guest_password'] . ")

";
    $body .= "<br><br>
Guest: " . $guest['guest_first_name'] . " " . $guest['guest_last_name'] . "<br>
Price: $" . number_format($thePrice['price'], 2, ".", ",") . "<br>
";
    if ($guest['insuranceCoverage'] > 0) $body .= "Accepted: Travel insurance protection.<br>
";
    $body .= '<br><b>Selections:</b><i> (current selections are always shown on your profile page)</i><br>
    
';
    $body .= $HTML->genEmail($guest['id']);
    if($depTable) {
        //$body.=$guest['guest_first_name']."'s Deposit / Payment Schedule:";
        $body .= $depTable;
    }

} // end outer guest for loop




/* DEBUGGING ************************************************************************************************************/
if(isset($_SERVER['DBSTEVE'])&&$_SERVER['DBSTEVE']=='1') {$YY=explode("/",__FILE__);$PP=__LINE__.":".str_replace(".php","",$YY[count($YY)-1]);
PC::debug($online,$PP." IK "); }  /* END DEBUG********************************************************************************************* */



if ($online['noteConfirmed'] || $clubtext['noteConfirmed']) {
    if ($clubtext['noteConfirmed']) {
        $body .= "<br>" . $clubtext['noteConfirmed'];
    } else {
        $body .= "<BR>" . $online['noteConfirmed'];
    }
}


if ($online['notePayments'] || $clubtext['notePayments'] || $online['noteXL'] || $clubtext['noteXL'] || $online['tandc'] || $clubtext['tandc']) {
    $body .= "<h3 style='color:green;'>You have agreed to the following:</h3>";
}

if ($online['notePayments'] || $clubtext['notePayments']) {
    $body .= "<h3>Payment Policy</h3>";
    if ($clubtext['notePayments']) {
        $body .= $clubtext['notePayments'];
    } else {
        $body .= $online['notePayments'];
    }

}


if ($online['noteXL'] || $clubtext['noteXL']) {
    $body .= "<h3>Cancellation Terms</h3>";
    if ($clubtext['noteXL']) {
        $body .= $clubtext['noteXL'];
    } else {
        $body .= $online['noteXL'];
    }
}
if ($online['tandc'] || $clubtext['tandc']) {
    $body .= "<h3>Terms and Conditions</h3>";
    if ($clubtext['tandc']) {
        $body .= $clubtext['tandc'];
    } else {
        $body .= $online['tandc'];
    }
}


/* DEBUGGING ************************************************************************************************************/
if(isset($_SERVER['DBSTEVE'])&&$_SERVER['DBSTEVE']=='1') {$YY=explode("/",__FILE__);$PP=__LINE__.":".str_replace(".php","",$YY[count($YY)-1]);
    PC::debug($body,$PP."body"); }  /* END DEBUG********************************************************************************************* */
//exit;

$email = array($lg['guest_email'] => $lg['guest_first_name'] . " " . $lg['guest_last_name']);

//require_once($Page->swiftMail);
$message = Swift_Message::newInstance()
    ->setSubject('Trip Registration Receipt - ' . $lg['guest_first_name'] . ' ' . $lg['guest_last_name'] . " - party of ".count($gid))
    ->setFrom(array('do-not-reply@sportsamerica.com' => 'Sports America - do not reply'))
    ->setTo($email)
    ->setBody($body, 'text/html');

$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
    ->setUsername('online@sportsamerica.com')
    ->setPassword('Spo1Ame1');

// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
$result = $mailer->send($message);
$_SESSION['firstView'] = $email;

if ($lg['wasDeleted'] == 2 && $lg['guest_usingcc']) {
    $timer = time() + (60 * 15);
    $Page->updateSQL("guests", "depositTimer", $timer, "id", $uid);

    $query = "SELECT * FROM guestPayment WHERE guest_id=? ORDER BY payDate LIMIT 1";
    $q = $Page->DB->prepare($query);
    unset($var);//vars
    $var[0] = $uid;
    try {
        $q->execute($var);
    } catch (PDOException $E) {
        if (isset($_SERVER['DBSTEVE']) && $_SERVER['DBSTEVE'] == '1') PC::debug($E->getMessage(), "SQLERROR");
    }
    $payment = $q->fetch(PDO::FETCH_ASSOC);

    $url = "https://www.sportsamerica.com/regdev/profile-charge-ems2.php?charge=" . $payment['payID'] . "&init=1";
    echo $url;

} else {
    $Page->updateSQL("guests", "wasDeleted", null, "id", $uid);

    echo $profile;
}


