<?php
require_once '../config/database.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

$email = trim($_POST['email'] ?? '');

if (empty($email)) {
    echo json_encode(['success' => false, 'message' => 'Email is required']);
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['success' => false, 'message' => 'Invalid email format']);
    exit;
}

try {
    $pdo = getDBConnection();
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? '';
    
    // Rate limiting - max 3 reset attempts per hour per IP
    if (!checkRateLimit($ip_address, 'password_reset', 3, 3600)) {
        echo json_encode(['success' => false, 'message' => 'Too many reset attempts. Please try again later.']);
        exit;
    }
    
    // Find admin by email
    $stmt = $pdo->prepare("SELECT id, email, first_name, last_name FROM admins WHERE email = ? AND status = 'active'");
    $stmt->execute([$email]);
    $admin = $stmt->fetch();
    
    if (!$admin) {
        // Always show success message for security (don't reveal if email exists)
        echo json_encode(['success' => true, 'message' => 'If this email exists, a reset link has been sent.']);
        
        // Log the attempt
        logActivity(null, 'password_reset', "Password reset attempt for non-existent email: {$email}");
        exit;
    }
    
    // Generate reset token
    $token = bin2hex(random_bytes(32));
    $expires = date('Y-m-d H:i:s', time() + 3600); // 1 hour expiry
    
    // Store reset token
    $stmt = $pdo->prepare("
        UPDATE admins 
        SET password_reset_token = ?, 
            password_reset_expires = ? 
        WHERE id = ?
    ");
    $stmt->execute([$token, $expires, $admin['id']]);
    
    // Create reset link
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'];
    $script_dir = dirname($_SERVER['SCRIPT_NAME']);
    $reset_link = "{$protocol}://{$host}{$script_dir}/reset-password-confirm.php?token={$token}";
    
    // Email content
    $subject = "Password Reset Request - KSO Admin";
    $message = "
    <html>
    <head>
        <title>Password Reset Request</title>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background: #007bff; color: white; padding: 20px; text-align: center; }
            .content { padding: 20px; background: #f8f9fa; }
            .button { display: inline-block; padding: 12px 24px; background: #007bff; color: white; text-decoration: none; border-radius: 4px; }
            .footer { padding: 20px; text-align: center; font-size: 12px; color: #666; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h2>Password Reset Request</h2>
            </div>
            <div class='content'>
                <p>Hello {$admin['first_name']} {$admin['last_name']},</p>
                <p>We received a request to reset your password for your KSO Admin account.</p>
                <p>Click the button below to reset your password:</p>
                <p><a href='{$reset_link}' class='button'>Reset Password</a></p>
                <p>Or copy and paste this link into your browser:</p>
                <p>{$reset_link}</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>
            </div>
            <div class='footer'>
                <p>This is an automated message from KSO Admin System.</p>
            </div>
        </div>
    </body>
    </html>
    ";
    
    // Email headers
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
    $headers .= "From: KSO Admin <noreply@ksochandigarh.org>\r\n";
    $headers .= "Reply-To: noreply@ksochandigarh.org\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion();
    
    // Send email
    $mail_sent = mail($email, $subject, $message, $headers);
    
    if ($mail_sent) {
        // Log successful reset request
        logActivity($admin['id'], 'password_reset', 'Password reset email sent', 'medium');
        
        echo json_encode(['success' => true, 'message' => 'Password reset link has been sent to your email.']);
    } else {
        // Log email failure
        logActivity($admin['id'], 'password_reset', 'Password reset email failed to send', 'high');
        
        echo json_encode(['success' => false, 'message' => 'Failed to send reset email. Please try again.']);
    }
    
} catch (Exception $e) {
    error_log("Password reset error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Password reset system temporarily unavailable']);
}
?>
