<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Admin Initiated Password Reset
 * Developer: JOACHIM'S INNOTECH
 */

// Initialize system
require_once dirname(__DIR__, 2) . '/config/config.php';
require_once dirname(__DIR__, 2) . '/config/constants.php';
require_once dirname(__DIR__, 2) . '/config/database.php';
require_once dirname(__DIR__, 2) . '/config/helpers.php';
require_once dirname(__DIR__, 2) . '/config/auth.php';
require_once dirname(__DIR__, 2) . '/config/csrf.php';
require_once dirname(__DIR__, 2) . '/config/mailer.php';

// Require authentication and permission
require_auth();
require_permission('users.edit');

// Get current user
$current_user = current_user();

// Handle POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    set_flash_message('danger', 'Invalid request method');
    redirect('admin/users/index.php');
}

// Verify CSRF token
if (!verify_csrf_token($_POST[CSRF_TOKEN_NAME] ?? '')) {
    set_flash_message('danger', 'Invalid security token. Please try again.');
    redirect('admin/users/index.php');
}

// Get user ID
$user_id = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;

if (!$user_id) {
    set_flash_message('danger', 'Invalid user ID');
    redirect('admin/users/index.php');
}

// Prevent resetting own password through this method
if ($user_id == $current_user['user_id']) {
    set_flash_message('danger', 'Please use the profile page to change your own password');
    redirect('admin/users/view.php?id=' . $user_id);
}

// Get user data
$user = db_fetch_one("SELECT user_id, username, email, first_name FROM users WHERE user_id = ?", [$user_id]);

if (!$user) {
    set_flash_message('danger', 'User not found');
    redirect('admin/users/index.php');
}

// Check if user is active
$is_active = db_fetch_value("SELECT is_active FROM users WHERE user_id = ?", [$user_id]);
if (!$is_active) {
    set_flash_message('warning', 'Cannot reset password for inactive user. Activate the user first.');
    redirect('admin/users/view.php?id=' . $user_id);
}

try {
    begin_transaction();
    
    // Generate reset token
    $token = bin2hex(random_bytes(32));
    $expires = date(DATETIME_FORMAT, time() + PASSWORD_RESET_EXPIRY);
    
    // Save token to database
    db_update('users', [
        'password_reset_token' => $token,
        'password_reset_expires' => $expires
    ], 'user_id = ?', [$user_id]);
    
    // Send reset email
    $reset_link = base_url('reset-password.php?token=' . urlencode($token));
    
    $email_vars = [
        'first_name' => $user['first_name'],
        'username' => $user['username'],
        'reset_link' => $reset_link,
        'expiry_hours' => PASSWORD_RESET_EXPIRY / 3600,
        'admin_name' => $current_user['first_name'] . ' ' . $current_user['last_name']
    ];
    
    // Use a special template for admin-initiated resets
    $subject = "Password Reset Requested by Administrator - Ruhondo Beach Resort";
    
    $body = "
    <html>
    <head>
        <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: #f9f9f9; }
            .button { display: inline-block; padding: 10px 20px; background: #007bff; color: white; text-decoration: none; border-radius: 5px; }
            .footer { margin-top: 20px; font-size: 12px; color: #666; text-align: center; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h2>Password Reset Request</h2>
            </div>
            <div class='content'>
                <p>Hello {$user['first_name']},</p>
                
                <p>An administrator has requested a password reset for your account at <strong>Ruhondo Beach Resort</strong>.</p>
                
                <p><strong>Username:</strong> {$user['username']}<br>
                <strong>Requested by:</strong> {$email_vars['admin_name']}</p>
                
                <p>To reset your password, click the button below:</p>
                
                <p style='text-align: center;'>
                    <a href='{$reset_link}' class='button'>Reset Password</a>
                </p>
                
                <p>Or copy and paste this link into your browser:<br>
                <small>{$reset_link}</small></p>
                
                <p><strong>Note:</strong> This link will expire in {$email_vars['expiry_hours']} hour(s).</p>
                
                <p>If you did not request this password reset, please contact your system administrator immediately.</p>
            </div>
            <div class='footer'>
                <p>&copy; " . date('Y') . " Ruhondo Beach Resort. All rights reserved.</p>
            </div>
        </div>
    </body>
    </html>
    ";
    
    $alt_body = "Hello {$user['first_name']},\n\n";
    $alt_body .= "An administrator has requested a password reset for your account at Ruhondo Beach Resort.\n\n";
    $alt_body .= "Username: {$user['username']}\n";
    $alt_body .= "Requested by: {$email_vars['admin_name']}\n\n";
    $alt_body .= "To reset your password, visit: {$reset_link}\n\n";
    $alt_body .= "This link will expire in {$email_vars['expiry_hours']} hour(s).\n\n";
    $alt_body .= "If you did not request this password reset, please contact your system administrator immediately.";
    
    $sent = send_email($user['email'], $subject, $body, $alt_body);
    
    if (!$sent) {
        throw new Exception('Failed to send reset email');
    }
    
    // Audit log
    audit_log($current_user['user_id'], 'password_reset_admin', 'users', $user_id, null, [
        'reset_by' => $current_user['user_id'],
        'reset_at' => date(DATETIME_FORMAT)
    ]);
    
    // Create notification for user
    create_notification(
        $user_id,
        NOTIFICATION_WARNING,
        'Password Reset Requested',
        'An administrator has requested a password reset for your account. Check your email for instructions.'
    );
    
    commit_transaction();
    
    set_flash_message('success', "Password reset link has been sent to {$user['email']}");
    
} catch (Exception $e) {
    rollback_transaction();
    log_message("Admin password reset failed: " . $e->getMessage(), 'ERROR');
    set_flash_message('danger', 'Failed to reset password: ' . $e->getMessage());
}

// Redirect back to user view
redirect('admin/users/view.php?id=' . $user_id);