<?php
require_once '../includes/config.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

// Redirect if already logged in
if (isLoggedIn()) {
    header('Location: ../');
    exit();
}

$token = $_GET['token'] ?? '';
$valid_token = false;
$email = '';

// Validate token
if ($token) {
    $stmt = $pdo->prepare("SELECT email FROM password_resets WHERE token = ? AND created_at > NOW() - INTERVAL 1 HOUR");
    $stmt->execute([$token]);
    $reset = $stmt->fetch();
    
    if ($reset) {
        $valid_token = true;
        $email = $reset['email'];
    }
}

// Handle password reset
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password'])) {
    if (!$valid_token) {
        $_SESSION['error_message'] = "Invalid or expired reset token.";
        header("Location: login.php");
        exit();
    }
    
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    
    if ($password !== $confirm_password) {
        $_SESSION['error_message'] = "Passwords do not match.";
    } else {
        // Update password
        $password_hash = password_hash($password, PASSWORD_DEFAULT);
        
        $pdo->beginTransaction();
        try {
            // Update user password
            $stmt = $pdo->prepare("UPDATE users SET password_hash = ? WHERE email = ?");
            $stmt->execute([$password_hash, $email]);
            
            // Delete used token
            $pdo->prepare("DELETE FROM password_resets WHERE token = ?")->execute([$token]);
            
            $pdo->commit();
            
            $_SESSION['success_message'] = "Password updated successfully! Please login.";
            header("Location: login.php");
            exit();
        } catch (PDOException $e) {
            $pdo->rollBack();
            $_SESSION['error_message'] = "Error resetting password: " . $e->getMessage();
        }
    }
}

include '../includes/header.php';
?>

<div class="container py-5">
    <div class="row justify-content-center">
        <div class="col-md-6 col-lg-5">
            <div class="card shadow-sm">
                <div class="card-body p-5">
                    <div class="text-center mb-4">
                        <img src="../assets/images/logo.png" alt="JV Overseas" style="height: 60px;">
                        <h3 class="mt-3">Reset Password</h3>
                    </div>
                    
                    <?php if (!$valid_token): ?>
                        <div class="alert alert-danger">
                            Invalid or expired password reset link. Please request a new one.
                        </div>
                        <div class="text-center">
                            <a href="forgot-password.php" class="btn btn-primary">Request New Link</a>
                        </div>
                    <?php else: ?>
                        <?php displayMessages(); ?>
                        
                        <form method="post">
                            <div class="form-group">
                                <label for="password">New Password</label>
                                <input type="password" class="form-control" id="password" name="password" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="confirm_password">Confirm Password</label>
                                <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                            </div>
                            
                            <button type="submit" class="btn btn-primary btn-block">Reset Password</button>
                        </form>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include '../includes/footer.php'; ?>