<?php

include('../pg-connect.php'); // Good practice to keep db connection files out of web root
include('prohibited_passwords.php');


// The result to be inserted into the middle of the page
$output = '';
$error = '';


// Get URL parameter to check that there was a genuine password reset request - set a default value for error handling
$reset_code = '0';
if (isset($_GET['id'])) 
{
    $reset_code = $_GET['id'];
}


// Form for entering username to reset password
$form1 = '
    <style>#resetForm {background-color: #e9e9e9;margin:10px;padding:5px 15px 20px 15px;width:320px;} #resetForm label {font-weight:bold;} .resetInput {margin:5px 0px 5px 0px;width:320px;}</style>
    <form id="resetForm" action="reset_password.php?id='.$reset_code.'" method="post">
    <h3>Reset your password</h3>
    <p>Please enter your new password below:</p>';
$form2 = '
        <label for="password1">New password:</label><br/>
            <input type="password" id="password1" name="password1" placeholder="Please enter a new password" class="resetInput" oninput="checkPasswordStrength(value)" autofocus/><br/>
            <div id="passwordStrength" class="neutral" style="margin-top:5px;">Strength</div>
        <label for="password2">Confirm new password:</label><br/>
            <input type="password" name="password2" placeholder="Confirm your new password" class="resetInput" /><br/> 
        <button type="submit" name="submit" style="margin-top:5px;">Reset password</button>
    </form>
';


// Error message where reset_code is missing from URL
$errorURL = '<p class="error" style="padding:10px;">It appears that you have not yet requested your password to be reset.<br/><a href="forgot_password.php" class="forgottenReset">Please request a password reset.</a><p>';
$errorTime = '<p class="error" style="padding:10px;">The time period for resetting your password has expired.<br/><a href="forgot_password.php" class="forgottenReset">Please re-request a password reset.</a><p>';


 // Handle the form submission. 
if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{   

    // Validate and secure the form data:
	$problemForm = FALSE;
    $problemURL = FALSE;
    
    // Check for each value...
    if (empty($_POST['password1'])) 
    {
		$problemForm = TRUE;
		$error .= '<p class="error">Please enter a password</p>';
	}
	
	if ($_POST['password1'] != $_POST['password2']) 
    {
		$problemForm = TRUE;
		$error .= '<p class="error">Your password did not match your confirmed password!</p>';
	}
    
    if (strlen($_POST['password1']) < 6 ) 
    {
		$problemForm = TRUE;
		$error .= '<p class="error">Your password must be at least 6 characters</p>';
	}
    
    if (strlen($_POST['password1']) > 0 )
    {
        if (strpos($prohibited_passwords,$_POST['password1'])) 
        {
		$problemForm = TRUE;
		$error .= '<p class="error">This password cannot be used</p>';
	    }
    }
    
    if ($reset_code == '0') 
    {
		$problemURL = TRUE;
	}
    
    
    // If there are missing fields in the form
    if ($problemForm) 
    {
        $output = $form1.$error.$form2;  
    }
    
    // Problem - no reset_code in URL
    else if ($problemURL)
    {
        $output = $errorURL;
    }
    
    else 
    { // No problems with form fields or reset_code
    
        $password = trim(strip_tags($_POST['password1']));
        
        // Query database to further check that password reset request is legitimate & within the timeframe
        
            // Define the query:
            $query = "SELECT companyid, email, reset_expiry FROM Client WHERE reset_code = '".$reset_code."'";
            
                if ($r = pg_query($dbc,$query))  // Run the query.
                
                {

	               while ($row = pg_fetch_array($r)) 
                   {                        
                       // Check reset timeframe has not expired
                        $reset_expiry_valid = (strtotime($row['reset_expiry']) > strtotime(date("Y-m-d H:i:s")));
                        if(!$reset_expiry_valid) {$output = $errorTime; break;} 
                       
                        // Reset password
                        if($reset_expiry_valid)
                        {
                            $password_query = "SELECT client_update_password ('".$password."','".$reset_code."')";
                            $password_update = pg_query($dbc, $password_query);
                            
  
                            // Prepare confirmation email
                            $html_message = '<p>Your Precision Tracking password for Client Login has been reset. If you did not request your password to be reset, or you experience any other difficulties, please do not hesitate to <a href="http://www.precisiontracking.co.nz/contact_us.html" target="_blank">contact us</a> by phone on 0800 GPS 001 or via email at <a href="mailto:admin@precisiontracking.co.nz">admin@precisiontracking.co.nz</a>.';
                                        
                            // Insert email send details into email_outbox table where it will automatically be sent
                            $company_id = $row['companyid'];
                            $dest_address = $row['email'];
                            $email_query = "INSERT INTO email_outbox ( src_address, dest_address, company_id, subject, text_message, html_message )
								VALUES ( 'info@precisiontracking.co.nz','$dest_address','$company_id','Your password has been reset','','$html_message')";

                            $email_insert = pg_query($dbc, $email_query);
                            
                                if (pg_affected_rows($email_insert) == 1)
                            
                                    {
                                    // Success message for screen
                                    $output = '<p style="padding:10px;">Your password has been successfully reset.</p><p style="padding:10px;">You will be redirected to the client login page in approximately 10 seconds. If you are not automatically redirected, you can <a href="client_login.php">click here to proceed to the login page</a>.</p>';
                                
                                    
                                    // Redirect user to login page
                                    header('Refresh: 10; URL=client_login.php');
                                    }
                            
                                else
                                    {
                                    $output = '<p class="error">We are unable to reset your password at the moment. Please <a href="http://www.precisiontracking.co.nz/contact_us.html" target="_blank">contact us</a> by phone on 0800 GPS 001 or via email at <a href="mailto:admin@precisiontracking.co.nz">admin@precisiontracking.co.nz</a>.</p>';
                                    }
                            
                        } 
	               
                   } // End while

                } // End Query IF
  
    } // End no problems with form fields

 
} // End of form submission IF.



else // Print form as user has loaded page for first time
{
    $output = $form1.$form2;
}

?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">

<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<head>
<title>Reset password | Precision Tracking</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<meta name="DC.title" content="Order Confirm | Precision Tracking" />
<meta name="DC.format" content="text/html" />
<meta name="DC.language" content="en" />
<meta name="robots" content="noindex" />

<script type="text/javascript" src="js/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="js/youtube.js"></script>
<script type="text/javascript" src="js/jquery.fancybox/jquery.fancybox-1.3.0.pack.js"></script>
<link rel="stylesheet" href="js/ui.dialog.css" type="text/css" />
<link rel="stylesheet" href="js/jquery.fancybox/jquery.fancybox-1.3.0.css" type="text/css" media="screen" />
<link rel="stylesheet" href="stylesheets/cms.css" type="text/css" />
<link rel="stylesheet" href="stylesheets/precision_tracking.css" type="text/css" />
				<link rel="stylesheet" href="stylesheets/printable.css" media="print" type="text/css" />
			<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="http://www.precisiontracking.co.nz/stylesheets/ie7.css" />
<![endif]-->

<script type="text/javascript">
$(document).ready(function(){

    
	//Show content once loaded
	//$(window).load(function() {  document.getElementById("hideAll").style.display = "none"; });
});
</script>

<script type="text/javascript" src="js/bgstretcher.js"></script>
<link rel="stylesheet" href="js/bgstretcher.css" />
<script type="text/javascript">
	$(document).ready(function(){
		
		$(".headerPhoneNumSlideout").hide();
	$(".headerPhoneNum").click(function(){
	$(".headerPhoneNum").hide();
		$(".headerPhoneNumSlideout").toggle("slow");
		$(this).toggleClass("active");
		return false;
	});
	});
</script>

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-46593017-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

</head>
<body id="default" class="sitemap">

    <div id="wrap">

        <div id="main">

            <div class="container">
                <div class="bgContainer">

                    <div id="header">

                        <a href="index.html" class="logo"><img src="images/templates/logo.png" alt="" /></a>
                        
                        <div id="phoneNumberHeader">
                            <p><strong><a class="headerPhoneNum" href="#">Call <span>0800...</span></a></strong></p>
                        </div><!--#phoneNumberHeader-->
                        
                        <div class="headerPhoneNumSlideout">
                            <div id="phoneNumberHeader">
                                <p><strong>0800 GPS 001</strong></p>
                            </div><!--#phoneNumberHeader-->
                        </div><!--#headerPhoneNumSlideout-->
                        
                        <div id="navigation">
                            <ul>
                                <li>
                                    <a href="home.html" class="  menu">Home</a>
                                </li>
                                <li>
                                    <a href="what_is_ptnz.html" class="  menu">What is PTNZ</a>
                                </li>
                                <li>
                                    <a href="spreaders_and_sprayers.html" class="  menu">Spreaders &amp; Sprayers</a>
                                </li>
                                <li>
                                    <a href="fleet_management.html" class="  menu">Fleet Management</a>
                                </li>
                                <li>
                                    <a href="ruc_rebates.html" class="  menu">RUC Rebates</a>
                                </li>
                                <li>
                                    <a href="contact_us.html" class="  menu">Contact us</a>
                                </li>
                                <li>
                                    <a href="client_login.php" class="  menu">Client Login</a>
                                </li>
                            </ul>
                        </div><!--#navigation-->

                        <div class="siteSearchContainer">
                            <script type="text/javascript">function sval(){return $.trim($('#k').val()) ? true : false;}</script>
                            <span class="searchLabel">Search Site</span>
                            <form name="site_search_form" onsubmit="return sval()"
                                action="http://www.precisiontracking.co.nz/sitesearch" method="get" id="site_search_form">
                            <input name="k" id="k" onclick="$('#k[value=&quot;Search...&quot;]','#site_search_form').val('')" size="16" maxlength="255" class="siteSearchInput" value="Search..." />
                            <input type="image" src="images/icons/search_icon.png"
                             alt="GO" class="siteSearchSubmit" />
                            </form>
                        </div>

                    </div><!--#header-->

                    <div id="content">

                        <div id="centerCol">

                            <?php
                                
                                print $output;

                            ?>

                        </div><!--#centerCol-->
                            
                    </div><!--#content-->

                </div><!--.bgcontainer-->
            </div><!--.container-->

    	</div><!--#main-->

    </div><!--#wrap-->

    <div id="footer">
        <div class="container">
            <div class="bgContainer">

              
                <div class="footerCallout" id="footerMenuOne">

					<!--$this->component('menu_children',$all_open,$start_anchor,$display_top_level)-->
                    <ul>        <li>
            <a href="home.html" class="  menu">Home</a>
		</li>
        <li>
            <a href="what_is_ptnz.html" class="  menu">What is PTNZ</a>
		</li>
        <li>
            <a href="spreaders_and_sprayers.html" class="  menu">Spreaders &amp; Sprayers</a>
		</li>
        <li>
            <a href="fleet_management.html" class="  menu">Fleet Management</a>
		</li>
        <li>
            <a href="ruc_rebates.html" class="  menu">RUC Rebates</a>
		</li>
        <li>
            <a href="contact_us.html" class="  menu">Contact us</a>
		</li>
        <li>
            <a href="client_login.php" class="  menu">Client Login</a>
		</li>
</ul>                 
                <!--#footerMenu--></div>

                <div class="footerCallout" id="footerMenuTwo">

				<iframe scrolling="no" allowtransparency="1" frameborder="0" src="footer_enquiry.html" width="310" height="165"></iframe>

                <!--#footerMenu--></div>

                <div class="footerCallout" id="footerMenuThree">
				<img src="images/templates/footer_logo.jpg" alt="" />
                </div>
                
                <div class="footerCallout" id="footerMenuFour">
				<p>Client Login</p>
								<form action="/reports/login.jsp" method="post" class="loginForm">
                                  <label for="username">Username:</label>
                                  <input type="text" name="username" class="input">
                                  <label for="password">Password:</label>
                                  <input type="password" name="password" class="input">
                                  <input border="0" type="submit" value="Log In" class="input-button">
                                </form>
                </div>
                </div>
					

                <!--#footerMenu--></div>

                
        <div id="copyright">
            <p>Copyright &copy; 2015 Precision Tracking. All rights reserved | <a href="sitemap.html">Sitemap</a> | <a href="privacy.html">Privacy</a> | <a href="http://www.holloways.co.nz/" target="_blank">Website Design</a> by Holloways</p>
        </div>


            <!--.bgcontainer--></div>
        <!--.container--></div>
    <!--#footer--></div>

<script type="text/javascript" src="js/password-strength.js"></script>

<script type="text/javascript" src="js/jquery.validate.min.js"></script>

<script>
	$(document).ready(function() {
    
    // Custom validation rule
    $.validator.addMethod('prohibited_passwords', function (value, element) {
        return this.optional(element) || value.search(<?php $string = preg_replace('/\s+/', '', $prohibited_passwords); //print $string ?>);
    }, "This password cannot be used");

 
    // Rules & messages for client-side validation
	$('#resetForm').validate({
		rules : {
            password1 : {
                minlength : 6
            },
            password2 : {
                minlength : 6,
                equalTo : "#password1"
            }
        }
	}); // end validate
        
	}); // end ready
	</script>

<script>
    $(document).ready(function() {
        
        // Open any link with this class in fancybox overlay
        $(".forgottenReset").fancybox({
            'autoDimensions': false,
            'overlayShow': true,
            'overlayColor'  :   '#000',
            'type': 'iframe',
            'width': 480,
            'height': 220,
            'scrolling': 'no'
        });
    
    }); // end ready
</script>

</body>

</html>