<?php
session_start();
require_once '../layouts/dbconn.php';

// PHPMailer classes
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require_once '../vendor/phpmailer/src/Exception.php';
require_once '../vendor/phpmailer/src/PHPMailer.php';
require_once '../vendor/phpmailer/src/SMTP.php';

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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

// Verify user has permission to reset passwords
$current_user_id = $_SESSION['user_id'];
$current_user_role_sql = "SELECT ur.role_name, ur.role_id 
                          FROM users u 
                          JOIN user_roles ur ON u.role_id = ur.role_id 
                          WHERE u.user_id = ?";
$stmt = $conn->prepare($current_user_role_sql);
$stmt->bind_param("i", $current_user_id);
$stmt->execute();
$current_role_result = $stmt->get_result();
$current_user_role = $current_role_result->fetch_assoc();

$can_reset_password = false;
if ($current_user_role) {
    if ($current_user_role['role_name'] === 'Super Admin' || $current_user_role['role_name'] === 'Administrator') {
        $can_reset_password = true;
    } else {
        $perm_sql = "SELECT can_edit 
                     FROM role_permissions 
                     WHERE role_id = ? AND menu_id = (SELECT menu_id FROM menu_items WHERE menu_url = 'users.php' LIMIT 1)";
        $perm_stmt = $conn->prepare($perm_sql);
        $perm_stmt->bind_param("i", $current_user_role['role_id']);
        $perm_stmt->execute();
        $perm_result = $perm_stmt->get_result();
        $permissions = $perm_result->fetch_assoc();
        
        if ($permissions && $permissions['can_edit'] == 1) {
            $can_reset_password = true;
        }
    }
}

if (!$can_reset_password) {
    echo json_encode(['success' => false, 'message' => 'You do not have permission to reset passwords']);
    exit();
}

/**
 * Function to get email settings from system_settings table
 */
function getEmailSettings($conn) {
    $sql = "SELECT setting_key, setting_value FROM system_settings WHERE category = 'email'";
    $result = $conn->query($sql);
    
    $settings = [];
    while ($row = $result->fetch_assoc()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
    return $settings;
}

/**
 * Function to send password reset email
 */
function sendPasswordResetEmail($conn, $user_email, $user_name, $temp_password) {
    // Get email settings
    $email_settings = getEmailSettings($conn);
    
    // Check if email is enabled
    if (empty($email_settings['email_enabled']) || $email_settings['email_enabled'] != '1') {
        return ['success' => false, 'message' => 'Email notifications are disabled in system settings'];
    }
    
    // Validate required settings
    $required_settings = ['smtp_host', 'smtp_port', 'smtp_username', 'smtp_password', 'email_from'];
    foreach ($required_settings as $setting) {
        if (empty($email_settings[$setting])) {
            return ['success' => false, 'message' => "Email configuration incomplete: {$setting} not set"];
        }
    }
    
    try {
        $mail = new PHPMailer(true);
        
        // Server settings
        $mail->isSMTP();
        $mail->Host = $email_settings['smtp_host'];
        $mail->SMTPAuth = true;
        $mail->Username = $email_settings['smtp_username'];
        $mail->Password = $email_settings['smtp_password'];
        
        // Encryption
        if (!empty($email_settings['smtp_encryption']) && $email_settings['smtp_encryption'] == 'ssl') {
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        } else {
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        }
        
        $mail->Port = (int)$email_settings['smtp_port'];
        
        // Recipients
        $mail->setFrom(
            $email_settings['email_from'],
            $email_settings['email_from_name'] ?? 'ENT Hospital'
        );
        $mail->addAddress($user_email, $user_name);
        
        // Optional: Add reply-to if different from sender
        if (!empty($email_settings['email_reply_to'])) {
            $mail->addReplyTo($email_settings['email_reply_to']);
        }
        
        // Content
        $mail->isHTML(true);
        $mail->Subject = 'Password Reset - ENT Hospital Management System';
        
        // Get hospital name from settings
        $hospital_name_sql = "SELECT setting_value FROM system_settings WHERE setting_key = 'hospital_name' LIMIT 1";
        $hospital_result = $conn->query($hospital_name_sql);
        $hospital_name = 'ENT Hospital';
        if ($hospital_result && $hospital_result->num_rows > 0) {
            $row = $hospital_result->fetch_assoc();
            $hospital_name = $row['setting_value'];
        }
        
        // HTML Email Body
        $mail->Body = '
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
        }
        .container {
            max-width: 600px;
            margin: 20px auto;
            background: #ffffff;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        .header h1 {
            margin: 0;
            font-size: 24px;
        }
        .content {
            padding: 30px;
        }
        .password-box {
            background: #f8f9fa;
            border-left: 4px solid #667eea;
            padding: 20px;
            margin: 20px 0;
            border-radius: 5px;
        }
        .password {
            font-size: 24px;
            font-weight: bold;
            color: #667eea;
            letter-spacing: 2px;
            text-align: center;
            font-family: monospace;
        }
        .warning {
            background: #fff3cd;
            border-left: 4px solid #ffc107;
            padding: 15px;
            margin: 20px 0;
            border-radius: 5px;
        }
        .button {
            display: inline-block;
            padding: 12px 30px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            text-decoration: none;
            border-radius: 5px;
            margin: 20px 0;
            font-weight: bold;
        }
        .footer {
            background: #f8f9fa;
            padding: 20px;
            text-align: center;
            font-size: 12px;
            color: #6c757d;
            border-top: 1px solid #dee2e6;
        }
        .icon {
            font-size: 48px;
            margin-bottom: 10px;
        }
        ul {
            padding-left: 20px;
        }
        li {
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="icon">🔐</div>
            <h1>Password Reset</h1>
            <p style="margin: 10px 0 0 0; opacity: 0.9;">' . htmlspecialchars($hospital_name) . '</p>
        </div>
        
        <div class="content">
            <h2 style="color: #333; margin-top: 0;">Hello ' . htmlspecialchars($user_name) . ',</h2>
            
            <p>Your password has been reset by a system administrator. Below is your new temporary password:</p>
            
            <div class="password-box">
                <p style="margin: 0 0 10px 0; font-size: 14px; color: #6c757d;">Temporary Password:</p>
                <div class="password">' . htmlspecialchars($temp_password) . '</div>
            </div>
            
            <div class="warning">
                <strong>⚠️ Important Security Notice:</strong>
                <ul style="margin: 10px 0 0 0;">
                    <li>This is a temporary password and should be changed immediately upon login</li>
                    <li>For security reasons, you will be required to change this password on your next login</li>
                    <li>Do not share this password with anyone</li>
                    <li>If you did not request this password reset, please contact your system administrator immediately</li>
                </ul>
            </div>
            
            <p><strong>Next Steps:</strong></p>
            <ol>
                <li>Visit the hospital management system login page</li>
                <li>Enter your email and the temporary password above</li>
                <li>You will be prompted to create a new secure password</li>
            </ol>
            
            <center>
                <a href="' . (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]" . dirname($_SERVER['PHP_SELF']) . '/login.php" class="button">
                    Login Now
                </a>
            </center>
            
            <p style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #dee2e6; color: #6c757d; font-size: 14px;">
                <strong>Tips for creating a strong password:</strong><br>
                • Use at least 8 characters<br>
                • Include uppercase and lowercase letters<br>
                • Include numbers and special characters<br>
                • Avoid using personal information<br>
                • Don\'t reuse passwords from other accounts
            </p>
        </div>
        
        <div class="footer">
            <p style="margin: 0;">
                <strong>' . htmlspecialchars($hospital_name) . '</strong><br>
                This is an automated message, please do not reply to this email.<br>
                If you need assistance, please contact the IT support team.
            </p>
            <p style="margin: 10px 0 0 0;">
                © ' . date('Y') . ' ' . htmlspecialchars($hospital_name) . '. All rights reserved.
            </p>
        </div>
    </div>
</body>
</html>';
        
        // Plain text version for email clients that don't support HTML
        $mail->AltBody = "Hello {$user_name},\n\n"
                       . "Your password has been reset by a system administrator.\n\n"
                       . "Temporary Password: {$temp_password}\n\n"
                       . "IMPORTANT: This is a temporary password and must be changed immediately upon login.\n\n"
                       . "Please visit the login page and use this temporary password to access your account. "
                       . "You will be required to create a new password.\n\n"
                       . "If you did not request this password reset, please contact your system administrator immediately.\n\n"
                       . "Best regards,\n"
                       . "{$hospital_name}";
        
        // Send email
        $mail->send();
        
        return ['success' => true, 'message' => 'Email sent successfully'];
        
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Email sending failed: ' . $mail->ErrorInfo];
    }
}

try {
    // Get user ID
    $user_id = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
    
    if (!$user_id) {
        throw new Exception('Invalid user ID');
    }
    
    // Verify user exists
    $check_sql = "SELECT user_id, full_name, email FROM users WHERE user_id = ?";
    $stmt = $conn->prepare($check_sql);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        throw new Exception('User not found');
    }
    
    $user = $result->fetch_assoc();
    
    // Generate temporary password (8 characters: mix of uppercase, lowercase, numbers)
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $temp_password = '';
    for ($i = 0; $i < 8; $i++) {
        $temp_password .= $chars[random_int(0, strlen($chars) - 1)];
    }
    
    // Add at least one uppercase, one lowercase, and one number to ensure strength
    $temp_password = strtoupper($temp_password[0]) . substr($temp_password, 1, 6) . rand(0, 9);
    
    // Hash the password
    $password_hash = password_hash($temp_password, PASSWORD_BCRYPT);
    
    // Begin transaction
    $conn->begin_transaction();
    
    try {
        // Update user password and set flag to force password change
        $update_sql = "UPDATE users SET 
                        password_hash = ?,
                        login_attempts = 0,
                        password_reset_token = NULL,
                        password_reset_expires = NULL,
                        updated_at = NOW()
                       WHERE user_id = ?";
        
        $stmt = $conn->prepare($update_sql);
        $stmt->bind_param("si", $password_hash, $user_id);
        
        if (!$stmt->execute()) {
            throw new Exception('Failed to reset password');
        }
        
        // Log the activity
        $log_sql = "INSERT INTO activity_logs (user_id, action, entity_type, entity_id, description, ip_address, user_agent) 
                    VALUES (?, 'UPDATE', 'user', ?, ?, ?, ?)";
        $log_stmt = $conn->prepare($log_sql);
        $description = "Password reset for user: " . $user['full_name'];
        $ip_address = $_SERVER['REMOTE_ADDR'];
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $log_stmt->bind_param("iisss", $current_user_id, $user_id, $description, $ip_address, $user_agent);
        $log_stmt->execute();
        
        // Commit transaction
        $conn->commit();
        
        // Send email notification with new password
        $email_result = sendPasswordResetEmail($conn, $user['email'], $user['full_name'], $temp_password);
        
        if ($email_result['success']) {
            echo json_encode([
                'success' => true,
                'message' => 'Password reset successfully and email sent to user',
                'new_password' => $temp_password,
                'email_sent' => true
            ]);
        } else {
            // Password was reset but email failed
            echo json_encode([
                'success' => true,
                'message' => 'Password reset successfully but email sending failed: ' . $email_result['message'],
                'new_password' => $temp_password,
                'email_sent' => false,
                'email_error' => $email_result['message']
            ]);
        }
        
    } catch (Exception $e) {
        $conn->rollback();
        throw $e;
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>