<?php
/**
 * RESET PASSWORD PAGE
 * File: auth/reset-password.php
 * Handles password reset with token
 */

require_once '../app/Core/init.php';

// Redirect if already logged in
if (Auth::check()) {
    $user_type = $_SESSION['user_type'];
    if ($user_type === 'admin') {
        redirect('../admin/index.php');
    } elseif ($user_type === 'vendor') {
        redirect('../vendor/index.php');
    } elseif ($user_type === 'customer') {
        redirect('../index.php');
    }
}

$token = $_GET['token'] ?? '';
$errors = [];
$success = false;
$invalid_token = false;

// Verify token
$userModel = new User();
$user = null;

if (empty($token)) {
    $invalid_token = true;
} else {
    $user = $userModel->findByResetToken($token);
    
    if (!$user) {
        $invalid_token = true;
    }
}

// Handle password reset form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$invalid_token) {
    $csrf_token = $_POST['csrf_token'] ?? '';
    if (!Security::validateToken($csrf_token)) {
        $errors['general'] = 'Invalid security token. Please refresh and try again.';
    } else {
        $password = $_POST['password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';
        
        // Validate password
        if (empty($password)) {
            $errors['password'] = 'Password is required';
        } elseif (strlen($password) < 8) {
            $errors['password'] = 'Password must be at least 8 characters';
        } elseif (!preg_match('/[A-Z]/', $password)) {
            $errors['password'] = 'Password must contain at least one uppercase letter';
        } elseif (!preg_match('/[a-z]/', $password)) {
            $errors['password'] = 'Password must contain at least one lowercase letter';
        } elseif (!preg_match('/[0-9]/', $password)) {
            $errors['password'] = 'Password must contain at least one number';
        }
        
        if (empty($confirm_password)) {
            $errors['confirm_password'] = 'Please confirm your password';
        } elseif ($password !== $confirm_password) {
            $errors['confirm_password'] = 'Passwords do not match';
        }
        
        // If no errors, update password
        if (empty($errors)) {
            try {
                // Update password and clear reset token
                $result = $userModel->updatePassword($user['id'], password_hash($password, PASSWORD_BCRYPT));
                $userModel->clearResetToken($user['id']);
                
                if ($result) {
                    $success = true;
                } else {
                    $errors['general'] = 'Failed to update password. Please try again.';
                }
            } catch (Exception $e) {
                log_message("Reset password error: " . $e->getMessage(), 'error');
                $errors['general'] = 'An error occurred. Please try again.';
            }
        }
    }
}

$page_title = "Reset Password - " . APP_NAME;
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="../assets/images/favicon.png">
    <title><?= $page_title ?></title>
    <link href="../assets/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../assets/plugins/fontawesome/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>

<body>
    <!-- Header -->
    <?php include '../templates/layouts/frontend/header.php'; ?>
    
    <div class="container-fluid p-0">
        <div class="row g-0">
            <div class="col-xl-5">
                <div class="account-page-area p-4 p-md-5">
                    
                    <?php if ($success): ?>
                        <!-- Success Message -->
                        <div class="text-center">
                            <div class="mb-4">
                                <i class="fas fa-check-circle text-success" style="font-size: 64px;"></i>
                            </div>
                            <h2 class="fw-semibold mb-3">Password Reset Successful!</h2>
                            <p class="mb-4">Your password has been successfully reset. You can now sign in with your new password.</p>
                            <a href="login.php" class="btn btn-primary btn-lg">
                                <i class="fas fa-sign-in-alt me-2"></i>Sign In Now
                            </a>
                        </div>
                        
                    <?php elseif ($invalid_token): ?>
                        <!-- Invalid Token Message -->
                        <div class="text-center">
                            <div class="mb-4">
                                <i class="fas fa-times-circle text-danger" style="font-size: 64px;"></i>
                            </div>
                            <h2 class="fw-semibold mb-3">Invalid or Expired Link</h2>
                            <p class="mb-4">The password reset link is invalid or has expired. Please request a new one.</p>
                            <a href="forgot-password.php" class="btn btn-primary btn-lg">Request New Link</a>
                        </div>
                        
                    <?php else: ?>
                        <!-- Header -->
                        <div class="mb-4">
                            <h2 class="fw-semibold mb-2">Create New Password</h2>
                            <p class="text-muted">Enter your new password below. Make sure it's strong and memorable!</p>
                        </div>
                        
                        <!-- Display errors -->
                        <?php if (isset($errors['general'])): ?>
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <i class="fas fa-exclamation-circle me-2"></i>
                                <?= Security::escapeOutput($errors['general']) ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>
                        
                        <!-- Reset Password Form -->
                        <form method="POST" action="" class="register-form">
                            <?= Security::csrfField() ?>
                            <input type="hidden" name="token" value="<?= Security::escapeOutput($token) ?>">
                            
                            <!-- Password Field -->
                            <div class="mb-3">
                                <label class="form-label">New Password <span class="text-danger">*</span></label>
                                <div class="position-relative">
                                    <input id="password" type="password" name="password" 
                                           class="form-control <?= isset($errors['password']) ? 'is-invalid' : '' ?>" 
                                           placeholder="Enter new password" required>
                                    <i data-bs-toggle="#password" class="fa-regular fa-eye-slash toggle-password"></i>
                                </div>
                                <?php if (isset($errors['password'])): ?>
                                    <div class="invalid-feedback d-block"><?= $errors['password'] ?></div>
                                <?php endif; ?>
                                <small class="text-muted">Must be 8+ characters with uppercase, lowercase, and number</small>
                            </div>
                            
                            <!-- Confirm Password Field -->
                            <div class="mb-4">
                                <label class="form-label">Confirm New Password <span class="text-danger">*</span></label>
                                <div class="position-relative">
                                    <input id="confirmPassword" type="password" name="confirm_password" 
                                           class="form-control <?= isset($errors['confirm_password']) ? 'is-invalid' : '' ?>" 
                                           placeholder="Confirm new password" required>
                                    <i data-bs-toggle="#confirmPassword" class="fa-regular fa-eye-slash toggle-password"></i>
                                </div>
                                <?php if (isset($errors['confirm_password'])): ?>
                                    <div class="invalid-feedback d-block"><?= $errors['confirm_password'] ?></div>
                                <?php endif; ?>
                            </div>
                            
                            <!-- Submit Button -->
                            <button type="submit" class="btn btn-primary btn-lg w-100">
                                <i class="fas fa-lock me-2"></i>Reset Password
                            </button>
                        </form>
                        
                        <!-- Bottom Text -->
                        <div class="bottom-text text-center mt-4">
                            Remember your password? <a href="login.php" class="fw-medium text-decoration-underline">Sign In</a>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <div class="col-xl-7 d-none d-xl-block">
                <div class="background-image bg-light d-flex flex-column h-100 justify-content-center p-5 rounded-4" data-image-src="../assets/images/lines.svg">
                    <div class="py-5 text-center">
                        <div class="mb-5">
                            <h2 class="fw-semibold">Secure Your Account</h2>
                            <p>Create a strong password to keep your account safe</p>
                        </div>
                        <img src="../assets/images/png-img/login.png" alt="" class="img-fluid">
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Footer -->
    <?php include '../templates/layouts/frontend/footer.php'; ?>
    
    <!-- Scripts -->
    <script src="../assets/plugins/jQuery/jquery.min.js"></script>
    <script src="../assets/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../assets/js/script.js"></script>
    
    <script>
        // Toggle password visibility
        document.querySelectorAll('.toggle-password').forEach(icon => {
            icon.addEventListener('click', function() {
                const input = document.querySelector(this.getAttribute('data-bs-toggle'));
                if (input.type === 'password') {
                    input.type = 'text';
                    this.classList.remove('fa-eye-slash');
                    this.classList.add('fa-eye');
                } else {
                    input.type = 'password';
                    this.classList.remove('fa-eye');
                    this.classList.add('fa-eye-slash');
                }
            });
        });
    </script>
</body>
</html>
