<?php
session_start();
if (!isset($_SESSION['admin_logged_in'])) {
    header('Location: login.php');
    exit;
}
require_once '../src/config/db.php';
require_once '../src/includes/functions.php';
require_once 'includes/lang.php';

if (!isset($_GET['id']) || empty($_GET['id'])) {
    header('Location: users.php');
    exit;
}

$id = (int)$_GET['id'];
$user = get_user_by_id($pdo, $id);

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = trim($_POST['username']);
    $full_name = trim($_POST['full_name']);
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);

    if (!empty($username) && !empty($full_name)) {
        // Check if username changed and belongs to another user
        if ($username !== $user['username']) {
            $existing = get_user_by_username($pdo, $username);
            if ($existing) {
                $error = "اسم المستخدم هذا مستخدم بالفعل من قبل شخص آخر.";
            }
        }

        if (!isset($error)) {
            try {
                if (!empty($password)) {
                    // Update user including new password
                    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                    $stmt = $pdo->prepare("UPDATE users SET username = ?, password = ?, full_name = ?, email = ? WHERE id = ?");
                    $stmt->execute([$username, $hashed_password, $full_name, $email, $id]);
                } else {
                    // Update user excluding password
                    $stmt = $pdo->prepare("UPDATE users SET username = ?, full_name = ?, email = ? WHERE id = ?");
                    $stmt->execute([$username, $full_name, $email, $id]);
                }

                // If updating current logged-in user, update session variable
                if ($user['username'] === $_SESSION['admin_username']) {
                    $_SESSION['admin_username'] = $username;
                    $_SESSION['admin_name'] = $full_name;
                }

                header('Location: users.php?success=edit');
                exit;
            } catch (\PDOException $e) {
                $error = "حدث خطأ أثناء تحديث بيانات المستخدم: " . $e->getMessage();
            }
        }
    } else {
        $error = "يرجى تعبئة جميع الحقول المطلوبة (اسم المستخدم والاسم الكامل).";
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="<?php echo $t['lang']; ?>" dir="<?php echo $t['dir']; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $t['edit_user_title']; ?> - VAULTIXAI</title>
    <link rel="stylesheet" href="<?php echo $bootstrapCSS; ?>" crossorigin="anonymous">
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
    <?php
    $currentPage = 'users';
    include 'includes/sidebar.php';
    ?>
    
    <div class="main-content">
        <div class="topbar">
            <h1>✏️ <?php echo $t['edit_user_title']; ?></h1>
            <a href="users.php" class="btn btn-outline-secondary px-4 py-2"><?php echo $t['user_back_btn']; ?></a>
        </div>

        <?php if (isset($error)): ?>
            <div class="alert alert-danger fw-bold mb-4">⚠️ <?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <div class="table-card p-4 p-md-5 mx-auto" style="max-width:680px;">
            <form method="POST">
                <div class="mb-3">
                    <label for="full_name" class="form-label"><?php echo $t['user_fullname']; ?> *</label>
                    <input type="text" id="full_name" name="full_name" class="form-control form-control-lg" required value="<?php echo htmlspecialchars($user['full_name']); ?>">
                </div>
                
                <div class="mb-3">
                    <label for="username" class="form-label"><?php echo $t['user_username']; ?> *</label>
                    <input type="text" id="username" name="username" class="form-control form-control-lg" required value="<?php echo htmlspecialchars($user['username']); ?>" style="font-family: monospace;">
                </div>

                <div class="mb-3">
                    <label for="email" class="form-label"><?php echo $t['user_email']; ?></label>
                    <input type="email" id="email" name="email" class="form-control form-control-lg" value="<?php echo htmlspecialchars($user['email']); ?>" style="font-family: monospace;">
                </div>
                
                <div class="mb-4">
                    <label for="password" class="form-label"><?php echo $t['user_password']; ?> (<?php echo $isRTL ? 'اتركه فارغاً لعدم التغيير' : 'Leave blank to keep current'; ?>)</label>
                    <input type="password" id="password" name="password" class="form-control form-control-lg" placeholder="••••••••">
                </div>
                
                <div class="d-flex gap-3">
                    <button type="submit" class="btn btn-gold flex-grow-1 py-2 fw-bold fs-6">💾 <?php echo $t['user_save_btn']; ?></button>
                    <a href="users.php" class="btn btn-outline-secondary py-2 px-4"><?php echo $t['user_cancel_btn']; ?></a>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Bootstrap 5 JS Bundle CDN -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
</body>
</html>
