<?php
/**
 * Job Portal - Forgot Password Page
 * GHAMECC Choir Management Platform
 * 
 * This page allows users to reset their password by 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 = '';
$email = '';

// Handle password reset request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_password'])) {
    $email = trim($_POST['email']);
    
    logInfo("Password reset request initiated", [
        'email' => $email,
        'ip_address' => $_SERVER['REMOTE_ADDR'] ?? 'unknown'
    ]);
    
    // Validate email
    if (empty($email)) {
        $errors[] = 'Email address is required';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Please enter a valid email address';
    } else {
        // Check if user exists in job_portal_users
        $userQuery = "SELECT id, email, full_name, status FROM job_portal_users WHERE email = ? AND status = 'active'";
        $user = fetchRow($userQuery, [$email]);
        
        if ($user) {
            // Generate password reset token
            $resetToken = bin2hex(random_bytes(32));
            $resetExpiry = date('Y-m-d H:i:s', strtotime('+1 hour'));
            
            // Store reset token in database
            $updateQuery = "UPDATE job_portal_users SET 
                           reset_token = ?, 
                           reset_token_expiry = ?, 
                           updated_at = NOW() 
                           WHERE id = ?";
            
            $result = executeQuery($updateQuery, [$resetToken, $resetExpiry, $user['id']]);
            
            if ($result) {
                // Send password reset email
                $resetLink = "http://" . $_SERVER['HTTP_HOST'] . "/ghameccapp/jobs/reset-password.php?token=" . $resetToken;
                
                $emailSubject = "Password Reset - GHAMECC Job Portal";
                $emailBody = "
                <html>
                <head>
                    <title>Password Reset Request</title>
                </head>
                <body>
                    <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;'>
                        <h2 style='color: #0d6efd;'>Password Reset Request</h2>
                        <p>Hello " . htmlspecialchars($user['full_name']) . ",</p>
                        <p>We received a request to reset your password for your GHAMECC Job Portal account.</p>
                        <p>Click the link below to reset your password:</p>
                        <p><a href='" . $resetLink . "' style='background-color: #0d6efd; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>Reset Password</a></p>
                        <p>Or copy and paste this link into your browser:</p>
                        <p>" . $resetLink . "</p>
                        <p><strong>This link will expire in 1 hour.</strong></p>
                        <p>If you didn't request this password reset, please ignore this email.</p>
                        <hr>
                        <p style='color: #666; font-size: 12px;'>
                            This is an automated message from GHAMECC Job Portal.<br>
                            Please do not reply to this email.
                        </p>
                    </div>
                </body>
                </html>
                ";
                
                // For development, log the reset link instead of sending email
                logInfo("Password reset email would be sent", [
                    'user_id' => $user['id'],
                    'email' => $email,
                    'reset_link' => $resetLink,
                    'token_expiry' => $resetExpiry
                ]);
                
                // In production, you would send the actual email here
                // mail($email, $emailSubject, $emailBody, "From: noreply@ghamecc.org\r\nContent-Type: text/html; charset=UTF-8\r\n");
                
                $success = 'Password reset instructions have been sent to your email address. Please check your inbox and follow the instructions to reset your password.';
                
                // For development purposes, also show the reset link
                if (defined('DEVELOPMENT_MODE') || $_SERVER['SERVER_NAME'] === 'localhost') {
                    $success .= '<br><br><strong>Development Mode:</strong> <a href="' . $resetLink . '" target="_blank">Click here to reset password</a>';
                }
                
            } else {
                logError("Failed to store password reset token", [
                    'user_id' => $user['id'],
                    'email' => $email
                ]);
                $errors[] = 'An error occurred while processing your request. Please try again.';
            }
        } else {
            // Don't reveal whether email exists or not for security
            logInfo("Password reset requested for non-existent or inactive user", [
                'email' => $email
            ]);
            $success = 'If an account with that email address exists, password reset instructions have been sent.';
        }
    }
}

$pageTitle = 'Forgot 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;
        }
        .forgot-password-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        .forgot-password-header {
            background: linear-gradient(135deg, #0d6efd, #0056b3);
            color: white;
            padding: 2rem;
            text-align: center;
        }
        .forgot-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);
        }
        .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="forgot-password-card">
                    <div class="forgot-password-header">
                        <div class="mb-3">
                            <i class="fas fa-key fa-3x"></i>
                        </div>
                        <h2 class="mb-0">Forgot Password</h2>
                        <p class="mb-0 mt-2">Reset your GHAMECC Job Portal password</p>
                    </div>
                    
                    <div class="forgot-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 $success; ?>
                            </div>
                            <div class="text-center mt-4">
                                <a href="login.php" class="btn btn-outline-primary">
                                    <i class="fas fa-arrow-left me-2"></i>Back to Login
                                </a>
                            </div>
                        <?php else: ?>
                            <p class="text-muted mb-4">
                                Enter your email address and we'll send you instructions to reset your password.
                            </p>
                            
                            <form method="POST" action="forgot-password.php">
                                <div class="mb-4">
                                    <label for="email" class="form-label">
                                        <i class="fas fa-envelope me-2"></i>Email Address
                                    </label>
                                    <input type="email" 
                                           class="form-control form-control-lg" 
                                           id="email" 
                                           name="email" 
                                           value="<?php echo htmlspecialchars($email); ?>"
                                           placeholder="Enter your email address"
                                           required>
                                </div>
                                
                                <div class="d-grid mb-4">
                                    <button type="submit" name="reset_password" class="btn btn-primary btn-lg">
                                        <i class="fas fa-paper-plane me-2"></i>Send Reset Instructions
                                    </button>
                                </div>
                            </form>
                            
                            <div class="text-center">
                                <a href="login.php" class="back-link">
                                    <i class="fas fa-arrow-left me-2"></i>Back to Login
                                </a>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="text-center mt-4">
                    <p class="text-white-50">
                        Don't have an account? 
                        <a href="register.php" class="text-white">Register 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>
</body>
</html>
