<?php
include_once("layout/header.php");
require_once("include/userClass.php");
require_once("include/loginFunction.php");

if (@$_SESSION['acct_no']) {
    header("Location:./user/dashboard.php");
}

// SECURITY: Use POST instead of GET for sensitive token
if ($_SERVER['REQUEST_METHOD'] !== 'POST' && !isset($_GET['token'])) {
    header('Location: ./forgot-password.php');
    exit('Invalid request');
}

// SECURITY: Validate reset token from secure method
date_default_timezone_set('Asia/kolkata');
$date = date("Y-m-d");

// Token should come from POST or be in a secure session
$email = null;
$reset_token = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['email']) && isset($_POST['token'])) {
    // SECURITY: Validate CSRF token
    if (!SecurityUtils::verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        toast_alert("error", "CSRF token validation failed");
        exit;
    }
    
    $email = SecurityUtils::validateInput($_POST['email'], 'email');
    $reset_token = SecurityUtils::validateInput($_POST['token'], 'string', 100);
    
    if (!$email || !$reset_token) {
        toast_alert("error", "Invalid email or token format");
        exit;
    }
} else if (isset($_GET['token'])) {
    // Fallback for GET (less secure but acceptable for read-only token verification)
    $email = SecurityUtils::validateInput($_GET['email'] ?? '', 'email');
    $reset_token = SecurityUtils::validateInput($_GET['token'], 'string', 100);
}

if (!$email || !$reset_token) {
    toast_alert("error", "Sorry Something Went Wrong !");
    exit;
}

// SECURITY: Parameterized query
$log2 = "SELECT * FROM users WHERE acct_email = :email";
$stmt = $conn->prepare($log2);
$stmt->execute([':email' => $email]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$row) {
    // Don't reveal if email exists
    SecurityUtils::logSecurityEvent('PASSWORD_RESET_INVALID_EMAIL', ['email' => $email]);
    toast_alert("error", "Invalid reset link");
    exit;
}

// Verify token matches and hasn't expired
if ($row['resettoken'] !== $reset_token || (isset($row['resettokenexp']) && strtotime($row['resettokenexp']) < time())) {
    SecurityUtils::logSecurityEvent('PASSWORD_RESET_INVALID_TOKEN', ['email' => $email]);
    toast_alert("error", "Reset token has expired or is invalid");
    exit;
}

if (isset($_POST['update'])) {
    // SECURITY: Verify CSRF token again
    if (!SecurityUtils::verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        toast_alert("error", "CSRF token validation failed");
        exit;
    }
    
    // SECURITY: Rate limiting
    if (SecurityUtils::isRateLimited('password_reset', 3, 300)) {
        toast_alert("error", "Too many password reset attempts. Please try again in 5 minutes.");
        exit;
    }
    
    $new_password = $_POST['new_password'] ?? '';
    
    // SECURITY: Validate password strength
    $passwordValidation = SecurityUtils::validatePassword($new_password);
    if (!$passwordValidation['valid']) {
        toast_alert("error", $passwordValidation['message']);
        exit;
    }
    
    $new_password_hash = SecurityUtils::hashPassword($new_password);

    // SECURITY: Parameterized query
    $sql2 = "UPDATE users SET acct_password = :acct_password, resettoken = :resettoken, resettokenexp = :resettokenexp WHERE acct_email = :email";
    $passwordUpdate = $conn->prepare($sql2);
    $passwordUpdate->execute([
        ':acct_password' => $new_password_hash,
        ':resettoken' => NULL,
        ':resettokenexp' => NULL,
        ':email' => $email
    ]);

    if ($passwordUpdate->rowCount() > 0) {
        SecurityUtils::logSecurityEvent('PASSWORD_RESET_SUCCESS', ['email' => $email]);
        
        if ($page['twillio_status'] == '1') {
            $number = $row['acct_phone'];
            $messageText = "Security Alert: Your password has been changed successfully.";
            $sendSms->sendSmsCode($number, $messageText);
        }
        
        $msg1 = "
            <div class='alert alert-success'>
            <script type='text/javascript'>
                function Redirect() {
                    window.location='./login.php';
                }
                document.write ('');
                setTimeout('Redirect()', 4000);
            </script>
            <center><img src='./assets/images/loading.gif' width='180px'  /></center>
            <center><strong style='color:black;'>Your Password has been changed successfully. Please wait while we redirect you...</strong></center>
            </div>
        ";
    } else {
        toast_alert("error", "Sorry Something Went Wrong !");
    }
}

?>

<div class="form-container outer">
    <div class="form-form">
        <div class="form-form-wrap">
            <div class="form-container">
                <div class="form-content">
                    
                     <?php if (isset($msg1)) echo $msg1; ?>

                    <h1 class="">New Password</h1>
                   
                    <p class="">Enter your new password below.</p>
                 <!--   <img src="./assets/settings/<?=$page['image']?>" class="navbar-logo" alt="logo" width="20%"> -->

                    <form class="text-left" method="POST">
                        <div class="form">

                           <div id="password-field" class="field-wrapper input mb-2">
                                <div class="d-flex justify-content-between">
                                    <label for="password">New Password</label>
                                </div>
                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-lock"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>
                                <input name="new_password" minlength="6" maxlength="60" type="password" class="form-control" placeholder="Password">
                                <input type="hidden" name="email" class="form-control" value='.$email.'>
                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" id="toggle-password" class="feather feather-eye"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
                            </div>
                            
                            
                            
                            <div class="d-sm-flex justify-content-between">
                                <div class="field-wrapper">
                                    <button type="submit" class="btn btn-primary" name="update" >Update Password</button>
                                </div>
                            </div>
                        </div>
                    </form>

                </div>
            </div>
        </div>
    </div>
</div>

<?php

include_once("layout/footer.php");

?>

