<?php
/**
 * Job Portal - Reset Password Page
 * GHAMECC Choir Management Platform
 * 
 * This page handles password reset using the token from email.
 */

// Include database connection and functions
require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';

// Initialize variables
$errors = [];
$success = '';
$token = '';
$validToken = false;
$user = null;

// Get token from URL
if (isset($_GET['token'])) {
    $token = trim($_GET['token']);
    
    // Validate token format
    if (strlen($token) === 64 && ctype_xdigit($token)) {
        // Check if token exists and is not expired
        $tokenQuery = "SELECT id, email, full_name, reset_token, reset_token_expiry 
                       FROM job_portal_users 
                       WHERE reset_token = ? 
                       AND reset_token_expiry > NOW() 
                       AND status = 'active'";
        
        $user = fetchRow($tokenQuery, [$token]);
        
        if ($user) {
            $validToken = true;
            logInfo("Valid password reset token accessed", [
                'user_id' => $user['id'],
                'email' => $user['email']
            ]);
        } else {
            logInfo("Invalid or expired password reset token", [
                'token' => $token
            ]);
            $errors[] = 'Invalid or expired password reset link. Please request a new password reset.';
        }
    } else {
        $errors[] = 'Invalid password reset link format.';
    }
} else {
    $errors[] = 'No password reset token provided.';
}

// Handle password reset form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_password']) && $validToken) {
    $newPassword = $_POST['new_password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';
    
    // Validate passwords
    if (empty($newPassword)) {
        $errors[] = 'New password is required';
    } elseif (strlen($newPassword) < 8) {
        $errors[] = 'Password must be at least 8 characters long';
    } elseif (!preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/', $newPassword)) {
        $errors[] = 'Password must contain at least one uppercase letter, one lowercase letter, and one number';
    } elseif ($newPassword !== $confirmPassword) {
        $errors[] = 'Passwords do not match';
    } else {
        // Hash the new password
        $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
        
        // Update password and clear reset token
        $updateQuery = "UPDATE job_portal_users SET 
                       password = ?, 
                       reset_token = NULL, 
                       reset_token_expiry = NULL, 
                       updated_at = NOW() 
                       WHERE id = ?";
        
        $result = executeQuery($updateQuery, [$hashedPassword, $user['id']]);
        
        if ($result) {
            logInfo("Password reset completed successfully", [
                'user_id' => $user['id'],
                'email' => $user['email']
            ]);
            
            $success = 'Your password has been reset successfully. You can now log in with your new password.';
        } else {
            logError("Failed to update password", [
                'user_id' => $user['id'],
                'email' => $user['email']
            ]);
            $errors[] = 'An error occurred while resetting your password. Please try again.';
        }
    }
}

$pageTitle = 'Reset Password - GHAMECC Job Portal';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?></title>
    
    <?php include '../includes/favicon.php'; ?>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
        }
        .reset-password-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        .reset-password-header {
            background: linear-gradient(135deg, #0d6efd, #0056b3);
            color: white;
            padding: 2rem;
            text-align: center;
        }
        .reset-password-body {
            padding: 2rem;
        }
        .form-control:focus {
            border-color: #0d6efd;
            box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.25);
        }
        .btn-primary {
            background: linear-gradient(135deg, #0d6efd, #0056b3);
            border: none;
            padding: 12px 30px;
            font-weight: 600;
        }
        .btn-primary:hover {
            background: linear-gradient(135deg, #0056b3, #004085);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }
        .password-requirements {
            font-size: 0.875rem;
            color: #6c757d;
        }
        .password-requirements ul {
            margin: 0;
            padding-left: 1.2rem;
        }
        .back-link {
            color: #6c757d;
            text-decoration: none;
            font-size: 0.9rem;
        }
        .back-link:hover {
            color: #0d6efd;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-6 col-lg-5">
                <div class="reset-password-card">
                    <div class="reset-password-header">
                        <div class="mb-3">
                            <i class="fas fa-lock fa-3x"></i>
                        </div>
                        <h2 class="mb-0">Reset Password</h2>
                        <p class="mb-0 mt-2">Create a new password for your account</p>
                    </div>
                    
                    <div class="reset-password-body">
                        <?php if (!empty($errors)): ?>
                            <div class="alert alert-danger">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                <ul class="mb-0">
                                    <?php foreach ($errors as $error): ?>
                                        <li><?php echo htmlspecialchars($error); ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        <?php endif; ?>
                        
                        <?php if ($success): ?>
                            <div class="alert alert-success">
                                <i class="fas fa-check-circle me-2"></i>
                                <?php echo htmlspecialchars($success); ?>
                            </div>
                            <div class="text-center mt-4">
                                <a href="login.php" class="btn btn-primary">
                                    <i class="fas fa-sign-in-alt me-2"></i>Login Now
                                </a>
                            </div>
                        <?php elseif ($validToken): ?>
                            <p class="text-muted mb-4">
                                Hello <?php echo htmlspecialchars($user['full_name']); ?>, please enter your new password below.
                            </p>
                            
                            <form method="POST" action="reset-password.php?token=<?php echo htmlspecialchars($token); ?>">
                                <div class="mb-3">
                                    <label for="new_password" class="form-label">
                                        <i class="fas fa-key me-2"></i>New Password
                                    </label>
                                    <input type="password" 
                                           class="form-control form-control-lg" 
                                           id="new_password" 
                                           name="new_password" 
                                           placeholder="Enter new password"
                                           required>
                                </div>
                                
                                <div class="mb-4">
                                    <label for="confirm_password" class="form-label">
                                        <i class="fas fa-key me-2"></i>Confirm New Password
                                    </label>
                                    <input type="password" 
                                           class="form-control form-control-lg" 
                                           id="confirm_password" 
                                           name="confirm_password" 
                                           placeholder="Confirm new password"
                                           required>
                                </div>
                                
                                <div class="password-requirements mb-4">
                                    <strong>Password Requirements:</strong>
                                    <ul>
                                        <li>At least 8 characters long</li>
                                        <li>Contains at least one uppercase letter</li>
                                        <li>Contains at least one lowercase letter</li>
                                        <li>Contains at least one number</li>
                                    </ul>
                                </div>
                                
                                <div class="d-grid mb-4">
                                    <button type="submit" name="reset_password" class="btn btn-primary btn-lg">
                                        <i class="fas fa-save me-2"></i>Reset Password
                                    </button>
                                </div>
                            </form>
                        <?php endif; ?>
                        
                        <?php if (!$validToken || $success): ?>
                            <div class="text-center">
                                <a href="forgot-password.php" class="back-link">
                                    <i class="fas fa-arrow-left me-2"></i>Request New Reset Link
                                </a>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="text-center mt-4">
                    <p class="text-white-50">
                        Remember your password? 
                        <a href="login.php" class="text-white">Login here</a>
                    </p>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- Password validation script -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const newPassword = document.getElementById('new_password');
            const confirmPassword = document.getElementById('confirm_password');
            
            function validatePasswords() {
                if (confirmPassword.value && newPassword.value !== confirmPassword.value) {
                    confirmPassword.setCustomValidity('Passwords do not match');
                } else {
                    confirmPassword.setCustomValidity('');
                }
            }
            
            newPassword.addEventListener('input', validatePasswords);
            confirmPassword.addEventListener('input', validatePasswords);
        });
    </script>
</body>
</html>
