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

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check if user is admin
$user_role = $_SESSION['role_name'] ?? '';
if ($user_role !== 'Super Admin') {
    header('Location: index.php');
    exit();
}

$user_id = $_GET['id'] ?? 0;

// Get user details
$sql = "SELECT u.*, 
        CONCAT(u.first_name, ' ', COALESCE(u.middle_name, ''), ' ', u.last_name) as full_name
        FROM users u
        WHERE u.id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "User not found!";
    header('Location: list_users.php');
    exit();
}

$user = $result->fetch_assoc();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];
    $reset_method = $_POST['reset_method']; // 'manual' or 'auto'
    
    // Validate passwords match
    if ($new_password !== $confirm_password) {
        $_SESSION['error_message'] = "Passwords do not match!";
    } elseif (strlen($new_password) < 8) {
        $_SESSION['error_message'] = "Password must be at least 8 characters long!";
    } else {
        // Hash the new password
        $password_hash = password_hash($new_password, PASSWORD_DEFAULT);
        
        // Update password
        $update_sql = "UPDATE users SET password_hash = ?, updated_at = NOW() WHERE id = ?";
        $update_stmt = $conn->prepare($update_sql);
        $update_stmt->bind_param("si", $password_hash, $user_id);
        
        if ($update_stmt->execute()) {
            // Log activity
            $activity_sql = "INSERT INTO activity_logs (user_id, action_type, module, reference_id, new_values) 
                           VALUES (?, 'UPDATE', 'USER', ?, ?)";
            $activity_stmt = $conn->prepare($activity_sql);
            $new_values = json_encode(['password_reset' => true, 'reset_by' => $_SESSION['user_id']]);
            $activity_stmt->bind_param("iis", $_SESSION['user_id'], $user_id, $new_values);
            $activity_stmt->execute();
            
            // TODO: Send email notification to user
            // You can implement email notification here
            
            $_SESSION['success_message'] = "Password reset successfully for '{$user['full_name']}'!";
            
            // Copy password to clipboard data (for auto-generated passwords)
            if ($reset_method === 'auto') {
                $_SESSION['generated_password'] = $new_password;
            }
            
            header('Location: view_user.php?id=' . $user_id);
            exit();
        } else {
            $_SESSION['error_message'] = "Failed to reset password!";
        }
    }
}

// Generate random password
function generateRandomPassword($length = 12) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*';
    $password = '';
    for ($i = 0; $i < $length; $i++) {
        $password .= $chars[random_int(0, strlen($chars) - 1)];
    }
    return $password;
}

$generated_password = generateRandomPassword();
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Reset Password')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .password-field {
            position: relative;
        }
        
        .toggle-password {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #6c757d;
        }
        
        .password-strength {
            height: 5px;
            border-radius: 3px;
            margin-top: 0.5rem;
            transition: all 0.3s;
        }
        
        .strength-weak { background-color: #dc3545; width: 33%; }
        .strength-medium { background-color: #ffc107; width: 66%; }
        .strength-strong { background-color: #28a745; width: 100%; }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Users', 'title' => 'Reset Password')); ?>

                    <?php if (isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php 
                                echo $_SESSION['error_message']; 
                                unset($_SESSION['error_message']);
                            ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <?php if (isset($_SESSION['generated_password'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <h5 class="alert-heading">Password Generated Successfully!</h5>
                            <hr>
                            <p class="mb-2">The temporary password is:</p>
                            <div class="d-flex align-items-center gap-2">
                                <code class="fs-5 bg-light p-2 rounded flex-grow-1" id="generatedPasswordDisplay">
                                    <?php echo $_SESSION['generated_password']; ?>
                                </code>
                                <button class="btn btn-sm btn-primary" onclick="copyPassword()">
                                    <i class="ri-file-copy-line"></i> Copy
                                </button>
                            </div>
                            <p class="mt-2 mb-0">
                                <strong>Important:</strong> Share this password securely with the user.
                            </p>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                        <?php unset($_SESSION['generated_password']); ?>
                    <?php endif; ?>

                    <div class="row justify-content-center">
                        <div class="col-lg-8">
                            <div class="card">
                                <div class="card-header bg-primary">
                                    <h4 class="card-title mb-0 text-white">
                                        <i class="ri-lock-password-line me-2"></i>Reset User Password
                                    </h4>
                                </div>
                                <div class="card-body">
                                    <div class="alert alert-info" role="alert">
                                        <div class="d-flex align-items-center">
                                            <div class="flex-shrink-0 me-3">
                                                <?php if ($user['profile_photo_url']): ?>
                                                    <img src="<?php echo htmlspecialchars($user['profile_photo_url']); ?>" 
                                                         alt="<?php echo htmlspecialchars($user['full_name']); ?>" 
                                                         class="avatar-sm rounded-circle">
                                                <?php else: ?>
                                                    <div class="avatar-sm">
                                                        <span class="avatar-title rounded-circle bg-primary text-white">
                                                            <?php 
                                                            $name = trim($user['full_name']);
                                                            $parts = explode(' ', $name);
                                                            $initials = '';
                                                            foreach($parts as $part) {
                                                                if (!empty($part)) {
                                                                    $initials .= strtoupper(substr($part, 0, 1));
                                                                    if (strlen($initials) >= 2) break;
                                                                }
                                                            }
                                                            echo $initials ?: 'U';
                                                            ?>
                                                        </span>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                            <div class="flex-grow-1">
                                                <h6 class="mb-1">Resetting password for:</h6>
                                                <p class="mb-0">
                                                    <strong><?php echo htmlspecialchars($user['full_name']); ?></strong><br>
                                                    <small class="text-muted"><?php echo htmlspecialchars($user['email']); ?></small>
                                                </p>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Reset Method Tabs -->
                                    <ul class="nav nav-tabs nav-tabs-custom mb-3" role="tablist">
                                        <li class="nav-item">
                                            <a class="nav-link active" data-bs-toggle="tab" href="#manual" role="tab">
                                                <i class="ri-keyboard-line me-1"></i>Manual Password
                                            </a>
                                        </li>
                                        <li class="nav-item">
                                            <a class="nav-link" data-bs-toggle="tab" href="#auto" role="tab">
                                                <i class="ri-magic-line me-1"></i>Generate Password
                                            </a>
                                        </li>
                                    </ul>

                                    <div class="tab-content">
                                        <!-- Manual Password Tab -->
                                        <div class="tab-pane active" id="manual" role="tabpanel">
                                            <form method="POST" id="manualResetForm">
                                                <input type="hidden" name="reset_method" value="manual">
                                                
                                                <div class="mb-3">
                                                    <label class="form-label">New Password <span class="text-danger">*</span></label>
                                                    <div class="password-field">
                                                        <input type="password" class="form-control" name="new_password" 
                                                               id="manualNewPassword" required minlength="8"
                                                               placeholder="Enter new password">
                                                        <i class="ri-eye-line toggle-password" onclick="togglePassword('manualNewPassword', this)"></i>
                                                    </div>
                                                    <div class="password-strength" id="manualStrength"></div>
                                                    <small class="text-muted">Minimum 8 characters</small>
                                                </div>

                                                <div class="mb-3">
                                                    <label class="form-label">Confirm Password <span class="text-danger">*</span></label>
                                                    <div class="password-field">
                                                        <input type="password" class="form-control" name="confirm_password" 
                                                               id="manualConfirmPassword" required
                                                               placeholder="Confirm new password">
                                                        <i class="ri-eye-line toggle-password" onclick="togglePassword('manualConfirmPassword', this)"></i>
                                                    </div>
                                                </div>

                                                <div class="form-check mb-3">
                                                    <input class="form-check-input" type="checkbox" id="notifyUser">
                                                    <label class="form-check-label" for="notifyUser">
                                                        Send password reset notification email to user
                                                    </label>
                                                </div>

                                                <div class="d-flex gap-2">
                                                    <button type="submit" class="btn btn-primary">
                                                        <i class="ri-check-line me-1"></i>Reset Password
                                                    </button>
                                                    <a href="view_user.php?id=<?php echo $user_id; ?>" class="btn btn-secondary">
                                                        <i class="ri-close-line me-1"></i>Cancel
                                                    </a>
                                                </div>
                                            </form>
                                        </div>

                                        <!-- Auto Generate Password Tab -->
                                        <div class="tab-pane" id="auto" role="tabpanel">
                                            <form method="POST" id="autoResetForm">
                                                <input type="hidden" name="reset_method" value="auto">
                                                
                                                <div class="alert alert-warning" role="alert">
                                                    <i class="ri-information-line me-2"></i>
                                                    A secure random password will be generated automatically
                                                </div>

                                                <div class="mb-3">
                                                    <label class="form-label">Generated Password</label>
                                                    <div class="input-group">
                                                        <input type="text" class="form-control" id="autoPassword" 
                                                               name="new_password" value="<?php echo $generated_password; ?>" 
                                                               readonly>
                                                        <button class="btn btn-outline-secondary" type="button" 
                                                                onclick="regeneratePassword()">
                                                            <i class="ri-refresh-line"></i> Regenerate
                                                        </button>
                                                        <button class="btn btn-outline-primary" type="button" 
                                                                onclick="copyToClipboard('autoPassword')">
                                                            <i class="ri-file-copy-line"></i> Copy
                                                        </button>
                                                    </div>
                                                </div>

                                                <input type="hidden" name="confirm_password" id="autoConfirmPassword" 
                                                       value="<?php echo $generated_password; ?>">

                                                <div class="form-check mb-3">
                                                    <input class="form-check-input" type="checkbox" id="notifyUserAuto" checked>
                                                    <label class="form-check-label" for="notifyUserAuto">
                                                        Send temporary password to user via email
                                                    </label>
                                                </div>

                                                <div class="d-flex gap-2">
                                                    <button type="submit" class="btn btn-primary">
                                                        <i class="ri-check-line me-1"></i>Reset Password
                                                    </button>
                                                    <a href="view_user.php?id=<?php echo $user_id; ?>" class="btn btn-secondary">
                                                        <i class="ri-close-line me-1"></i>Cancel
                                                    </a>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <script>
        // Toggle password visibility
        function togglePassword(fieldId, icon) {
            const field = document.getElementById(fieldId);
            const type = field.getAttribute('type') === 'password' ? 'text' : 'password';
            field.setAttribute('type', type);
            icon.className = type === 'password' ? 'ri-eye-line toggle-password' : 'ri-eye-off-line toggle-password';
        }

        // Check password strength
        document.getElementById('manualNewPassword')?.addEventListener('input', function() {
            const password = this.value;
            const strengthBar = document.getElementById('manualStrength');
            
            if (password.length === 0) {
                strengthBar.className = 'password-strength';
                return;
            }
            
            let strength = 0;
            if (password.length >= 8) strength++;
            if (password.match(/[a-z]/) && password.match(/[A-Z]/)) strength++;
            if (password.match(/[0-9]/)) strength++;
            if (password.match(/[^a-zA-Z0-9]/)) strength++;
            
            if (strength <= 2) {
                strengthBar.className = 'password-strength strength-weak';
            } else if (strength === 3) {
                strengthBar.className = 'password-strength strength-medium';
            } else {
                strengthBar.className = 'password-strength strength-strong';
            }
        });

        // Validate password match
        document.getElementById('manualResetForm')?.addEventListener('submit', function(e) {
            const password = document.getElementById('manualNewPassword').value;
            const confirm = document.getElementById('manualConfirmPassword').value;
            
            if (password !== confirm) {
                e.preventDefault();
                alert('Passwords do not match!');
                return false;
            }
        });

        // Regenerate password
        function regeneratePassword() {
            fetch('generate_password_api.php')
                .then(response => response.json())
                .then(data => {
                    document.getElementById('autoPassword').value = data.password;
                    document.getElementById('autoConfirmPassword').value = data.password;
                })
                .catch(() => {
                    // Fallback: generate on client side
                    const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*';
                    let password = '';
                    for (let i = 0; i < 12; i++) {
                        password += chars.charAt(Math.floor(Math.random() * chars.length));
                    }
                    document.getElementById('autoPassword').value = password;
                    document.getElementById('autoConfirmPassword').value = password;
                });
        }

        // Copy to clipboard
        function copyToClipboard(elementId) {
            const element = document.getElementById(elementId);
            element.select();
            element.setSelectionRange(0, 99999);
            document.execCommand('copy');
            
            // Show feedback
            const btn = event.target.closest('button');
            const originalText = btn.innerHTML;
            btn.innerHTML = '<i class="ri-check-line"></i> Copied!';
            setTimeout(() => {
                btn.innerHTML = originalText;
            }, 2000);
        }

        // Copy generated password from alert
        function copyPassword() {
            const text = document.getElementById('generatedPasswordDisplay').textContent;
            navigator.clipboard.writeText(text).then(() => {
                const btn = event.target.closest('button');
                btn.innerHTML = '<i class="ri-check-line"></i> Copied!';
                setTimeout(() => {
                    btn.innerHTML = '<i class="ri-file-copy-line"></i> Copy';
                }, 2000);
            });
        }
    </script>
</body>
</html>