<?php
/**
 * Admin - Change User Password
 * Allows admin and user_admin to change any user's password
 */

session_start();
require_once '../db_connect.php';

// Allow both admin and user_admin roles
if(!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], ['admin', 'user_admin'])) {
    header('Location: ../login');
    exit;
}

$error = '';
$success = '';
$user = null;

// Get user ID from URL
$user_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if($user_id <= 0) {
    header('Location: users.php');
    exit;
}

// Get user details
$stmt = $conn->prepare("SELECT id, username, full_name, email, role FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

if(!$user) {
    header('Location: users.php?error=User not found');
    exit;
}

// user_admin cannot change admin passwords
if($_SESSION['role'] == 'user_admin' && $user['role'] == 'admin') {
    header('Location: users.php?error=You cannot change admin passwords');
    exit;
}

// Handle password change
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    if(strlen($new_password) < 6) {
        $error = 'Password must be at least 6 characters';
    } elseif($new_password !== $confirm_password) {
        $error = 'Passwords do not match';
    } else {
        // Hash and update password
        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);

        $update_stmt = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
        $update_stmt->bind_param("si", $hashed_password, $user_id);

        if($update_stmt->execute()) {
            // Log activity
            $admin_id = $_SESSION['user_id'];
            $log_desc = "Password changed for user: {$user['username']} by " . ($_SESSION['role'] == 'admin' ? 'Admin' : 'User Admin');
            mysqli_query($conn, "INSERT INTO activity_logs (user_id, action, description, ip_address) VALUES ($admin_id, 'password_changed', '$log_desc', '{$_SERVER['REMOTE_ADDR']}')");

            $success = "Password changed successfully for {$user['full_name']}!";
        } else {
            $error = 'Failed to change password: ' . mysqli_error($conn);
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Change Password - <?php echo htmlspecialchars($user['full_name']); ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../assets/font-awesome/css/all.min.css">
    <link href="../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <style>
        :root {
            --primary: #4f46e5;
            --success: #22c55e;
            --warning: #f59e0b;
            --danger: #ef4444;
        }
        body { font-family: 'Inter', sans-serif; background: #f1f5f9; }
        .main-content { margin-left: 280px; padding: 24px; }
        @media (max-width: 1024px) { .main-content { margin-left: 0; padding-top: 90px; } }

        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 16px;
            padding: 30px;
            margin-bottom: 24px;
            color: white;
        }
        .page-header h1 { font-size: 24px; font-weight: 700; margin: 0 0 8px; }
        .page-header p { margin: 0; opacity: 0.9; }

        .form-card {
            background: white;
            border-radius: 16px;
            padding: 32px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.05);
            max-width: 500px;
        }

        .user-info {
            background: #f8fafc;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 24px;
            border: 1px solid #e2e8f0;
        }
        .user-info h4 {
            font-size: 18px;
            font-weight: 600;
            color: #1e293b;
            margin: 0 0 8px;
        }
        .user-info p {
            font-size: 14px;
            color: #64748b;
            margin: 0;
        }
        .user-info .role-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            margin-top: 8px;
        }
        .role-admin { background: #fef3c7; color: #92400e; }
        .role-user_admin { background: #dbeafe; color: #1e40af; }
        .role-user { background: #d1fae5; color: #065f46; }
        .role-broker { background: #e0e7ff; color: #3730a3; }

        .form-group { margin-bottom: 20px; }
        .form-label {
            display: block;
            font-size: 13px;
            font-weight: 600;
            color: #334155;
            margin-bottom: 8px;
        }
        .form-control {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            font-size: 14px;
            transition: all 0.2s;
        }
        .form-control:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
        }

        .password-input {
            position: relative;
        }
        .password-input .toggle-password {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: #94a3b8;
            cursor: pointer;
        }
        .password-input .toggle-password:hover {
            color: var(--primary);
        }

        .btn {
            padding: 12px 24px;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 600;
            border: none;
            cursor: pointer;
            transition: all 0.2s;
        }
        .btn-primary {
            background: var(--primary);
            color: white;
        }
        .btn-primary:hover {
            background: #4338ca;
            transform: translateY(-1px);
        }
        .btn-outline {
            background: white;
            border: 2px solid #e2e8f0;
            color: #64748b;
        }
        .btn-outline:hover {
            background: #f8fafc;
        }

        .alert {
            padding: 14px 18px;
            border-radius: 10px;
            margin-bottom: 20px;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .alert-success { background: #d4edda; color: #155724; }
        .alert-danger { background: #f8d7da; color: #721c24; }

        .back-link {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            color: #64748b;
            text-decoration: none;
            font-size: 14px;
            margin-bottom: 16px;
        }
        .back-link:hover { color: var(--primary); }

        .password-requirements {
            background: #fffbeb;
            border: 1px solid #fcd34d;
            border-radius: 8px;
            padding: 12px 16px;
            margin-bottom: 20px;
        }
        .password-requirements h5 {
            font-size: 13px;
            font-weight: 600;
            color: #92400e;
            margin: 0 0 8px;
        }
        .password-requirements ul {
            margin: 0;
            padding-left: 20px;
            font-size: 12px;
            color: #78350f;
        }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <div class="main-content">
        <a href="users" class="back-link">
            <i class="fas fa-arrow-left"></i> Back to Users
        </a>

        <div class="page-header">
            <h1><i class="fas fa-key"></i> Change User Password</h1>
            <p>Reset password for a user account</p>
        </div>

        <?php if($error): ?>
        <div class="alert alert-danger">
            <i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($error); ?>
        </div>
        <?php endif; ?>

        <?php if($success): ?>
        <div class="alert alert-success">
            <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success); ?>
        </div>
        <?php endif; ?>

        <div class="form-card">
            <div class="user-info">
                <h4><?php echo htmlspecialchars($user['full_name']); ?></h4>
                <p><i class="fas fa-user"></i> <?php echo htmlspecialchars($user['username']); ?> &bull; <?php echo htmlspecialchars($user['email']); ?></p>
                <span class="role-badge role-<?php echo $user['role']; ?>">
                    <?php
                    $role_labels = [
                        'admin' => 'Full Admin',
                        'user_admin' => 'Payment Admin',
                        'user' => 'Regular User',
                        'broker' => 'Broker'
                    ];
                    echo $role_labels[$user['role']] ?? ucfirst($user['role']);
                    ?>
                </span>
            </div>

            <div class="password-requirements">
                <h5><i class="fas fa-info-circle"></i> Password Requirements</h5>
                <ul>
                    <li>At least 6 characters long</li>
                    <li>Use a mix of letters and numbers for better security</li>
                </ul>
            </div>

            <form method="POST">
                <div class="form-group">
                    <label class="form-label">New Password *</label>
                    <div class="password-input">
                        <input type="password" name="new_password" id="new_password" class="form-control" required placeholder="Enter new password" minlength="6">
                        <button type="button" class="toggle-password" onclick="togglePassword('new_password', this)">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Confirm Password *</label>
                    <div class="password-input">
                        <input type="password" name="confirm_password" id="confirm_password" class="form-control" required placeholder="Confirm new password" minlength="6">
                        <button type="button" class="toggle-password" onclick="togglePassword('confirm_password', this)">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                </div>

                <div style="display: flex; gap: 12px; margin-top: 24px;">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Change Password
                    </button>
                    <a href="users" class="btn btn-outline">Cancel</a>
                </div>
            </form>
        </div>
    </div>

    <script src="../assets/vendor/jquery/jquery.min.js"></script>
    <script src="../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        function togglePassword(inputId, btn) {
            const input = document.getElementById(inputId);
            const icon = btn.querySelector('i');

            if(input.type === 'password') {
                input.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                input.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        }

        // Validate passwords match
        document.querySelector('form').addEventListener('submit', function(e) {
            const newPass = document.getElementById('new_password').value;
            const confirmPass = document.getElementById('confirm_password').value;

            if(newPass !== confirmPass) {
                e.preventDefault();
                alert('Passwords do not match!');
            }
        });
    </script>
</body>
</html>
