<?php
$page_title = "Reset Password";
require_once 'includes/header.php';

// Check if user is already logged in
if (isset($_SESSION['user_id'])) {
    header('Location: user/dashboard.php');
    exit();
}

$message = '';
$message_type = '';
$token_valid = false;
$user_id = null;

if (isset($_GET['token'])) {
    $token = $_GET['token'];
    $db = Database::getInstance()->connect();

    // Verify token
    $stmt = $db->prepare("
        SELECT id FROM users
        WHERE password_reset_token = ?
        AND password_reset_expiry > NOW()
        AND email_verified = 1
    ");
    $stmt->execute([$token]);
    $user = $stmt->fetch();

    if ($user) {
        $token_valid = true;
        $user_id = $user['id'];
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_password'])) {
    if (!$token_valid || !$user_id) {
        $message = "Invalid or expired reset token.";
        $message_type = "error";
    } else {
        $password = $_POST['password'];
        $confirm_password = $_POST['confirm_password'];

        if (empty($password) || strlen($password) < 8) {
            $message = "Password must be at least 8 characters long.";
            $message_type = "error";
        } elseif ($password !== $confirm_password) {
            $message = "Passwords do not match.";
            $message_type = "error";
        } else {
            $db = Database::getInstance()->connect();

            // Hash new password
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);

            // Update password and clear reset token
            $update_stmt = $db->prepare("
                UPDATE users SET
                    password = ?,
                    password_reset_token = NULL,
                    password_reset_expiry = NULL,
                    updated_at = NOW()
                WHERE id = ?
            ");
            $result = $update_stmt->execute([$hashed_password, $user_id]);

            if ($result) {
                $message = "Password has been reset successfully. You can now log in with your new password.";
                $message_type = "success";
                $token_valid = false; // Prevent form resubmission
            } else {
                $message = "Failed to reset password. Please try again.";
                $message_type = "error";
            }
        }
    }
}
?>

<!-- Start main-content -->
<section class="page-title" style="background-image: url(images/bg/page-title-bg.jpg);">
  <div class="auto-container">
    <div class="title-outer">
      <ul class="page-breadcrumb">
         <li><a href="index.php">Home</a></li>
        <li>Reset Password</li>
      </ul>
      <h1 class="title">Reset Password</h1>
    </div>
  </div>
</section>
<!-- end main-content -->

<section class="contact-details pt-120 pb-120">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-6 col-md-8 col-sm-10 col-12">
                <div class="inner-column right-column" style="margin: 0 auto; background: #ffffff; padding: 40px; border-radius: 12px; box-shadow: 0px 15px 40px rgba(0, 0, 0, 0.05); border: 1px solid rgba(0, 0, 0, 0.05);">
                    <div class="sec-title mb-30 text-center">
                        <h2 class="title splt-txt">Reset Password</h2>
                        <p class="text">Choose a secure new password for your account.</p>
                    </div>

                    <?php if ($message): ?>
                        <div class="alert <?php echo $message_type === 'success' ? 'alert-success' : 'alert-danger'; ?> mb-4" style="background-color: <?php echo $message_type === 'success' ? '#d4edda' : '#f8d7da'; ?>; border-color: <?php echo $message_type === 'success' ? '#c3e6cb' : '#f5c6cb'; ?>; color: <?php echo $message_type === 'success' ? '#155724' : '#721c24'; ?>; padding: 12px 20px; border-radius: 6px; font-size: 15px; border-left: 4px solid <?php echo $message_type === 'success' ? '#28a745' : '#dc3545'; ?>;">
                            <i class="fa-solid <?php echo $message_type === 'success' ? 'fa-circle-check' : 'fa-triangle-exclamation'; ?> me-2"></i> <?php echo htmlspecialchars($message); ?>
                        </div>
                    <?php endif; ?>

                    <?php if (!$token_valid && !$message): ?>
                        <div class="alert alert-warning mb-4" style="color: #856404; background-color: #fff3cd; border-color: #ffeeba; padding: 12px 20px; border-radius: 6px; font-size: 15px; border-left: 4px solid #ffc107;">
                            <i class="fa-solid fa-triangle-exclamation me-2"></i> This password reset link is invalid or has expired.
                             <a href="forgot-password.php" class="text-theme-color2" style="font-weight: 600; text-decoration: underline;">Request a new one.</a>
                        </div>
                    <?php elseif ($token_valid): ?>
                        <form method="POST" action="">
                            <input type="hidden" name="reset_password" value="1">
                            
                            <div class="type-feild">
                                <i class="fa-light fa-lock" style="color: var(--theme-color2); font-size: 18px; top: 12px;"></i>
                                <input type="password" name="password" required placeholder="New Password*" minlength="8" style="border-bottom: 1px solid rgba(92, 92, 91, 0.2); font-size: 16px; padding: 10px 10px 10px 35px; background: transparent; transition: all 0.3s ease;" onfocus="this.style.borderColor='var(--theme-color2)'" onblur="this.style.borderColor='rgba(92, 92, 91, 0.2)'">
                            </div>

                            <div class="type-feild">
                                <i class="fa-light fa-lock-keyhole" style="color: var(--theme-color2); font-size: 18px; top: 12px;"></i>
                                <input type="password" name="confirm_password" required placeholder="Confirm New Password*" minlength="8" style="border-bottom: 1px solid rgba(92, 92, 91, 0.2); font-size: 16px; padding: 10px 10px 10px 35px; background: transparent; transition: all 0.3s ease;" onfocus="this.style.borderColor='var(--theme-color2)'" onblur="this.style.borderColor='rgba(92, 92, 91, 0.2)'">
                            </div>

                            <div class="text-center">
                                <button type="submit" class="btn-two" style="width: 100%; border: none; border-radius: 6px; padding: 16px 20px; font-weight: 600; cursor: pointer; transition: all 0.3s ease;">Reset Password</button>
                            </div>
                        </form>
                    <?php endif; ?>

                    <div class="text-center mt-4">
                         <a href="login.php" class="text-decoration-none text-theme-color2" style="font-size: 15px; font-weight: 600;">Back to login</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<?php require_once 'includes/footerm.php'; ?>