<?php
require_once '../includes/functions.php';
requireLogin();
requireAdmin();

$error = '';
$success = '';

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

$id = $_GET['id'];
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ? AND role = 'user'");
$stmt->execute([$id]);
$user = $stmt->fetch();

if (!$user) {
    header("Location: manage_users.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['update_details'])) {
        $name = $_POST['name'];
        $email = $_POST['email'];
        $phone = $_POST['phone'];
        $username = $_POST['username'];
        $balance = $_POST['balance'];
        $status = $_POST['status'];

        // Validation
        if (empty($name) || empty($email) || empty($phone) || empty($username)) {
            $error = "Name, Email, Phone, and Username are required.";
        } else {
            // Check if email, phone, or username already exists for other users
            $stmt = $pdo->prepare("SELECT id FROM users WHERE (email = ? OR phone = ? OR username = ?) AND id != ?");
            $stmt->execute([$email, $phone, $username, $id]);
            if ($stmt->fetch()) {
                $error = "Email, Phone, or Username already exists for another user.";
            } else {
                $stmt = $pdo->prepare("UPDATE users SET name = ?, email = ?, phone = ?, username = ?, balance = ?, status = ? WHERE id = ?");
                if ($stmt->execute([$name, $email, $phone, $username, $balance, $status, $id])) {
                    $success = "User details updated successfully.";
                    // Refresh user data
                    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
                    $stmt->execute([$id]);
                    $user = $stmt->fetch();
                } else {
                    $error = "Failed to update user details.";
                }
            }
        }
    } elseif (isset($_POST['change_password'])) {
        $new_password = $_POST['new_password'];
        $confirm_password = $_POST['confirm_password'];

        if (empty($new_password)) {
            $error = "New password cannot be empty.";
        } elseif ($new_password !== $confirm_password) {
            $error = "Passwords do not match.";
        } else {
            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
            if ($stmt->execute([$hashed_password, $id])) {
                $success = "Password changed successfully.";
            } else {
                $error = "Failed to change password.";
            }
        }
    }
}

include '../includes/header.php';
?>

<div class="row animate-fade-in">
    <div class="col-md-12 mb-4">
        <div class="d-flex align-items-center gap-3">
            <a href="manage_users.php" class="btn btn-light rounded-pill border"><i class="fas fa-arrow-left"></i></a>
            <div>
                <h2 class="fw-bold m-0 text-primary">Edit User: <span class="text-dark"><?php echo htmlspecialchars($user['name']); ?></span></h2>
                <p class="text-muted small mb-0">Modify account details, balance, or security settings.</p>
            </div>
        </div>
    </div>

    <div class="col-lg-8">
        <div class="glass-card p-5 mb-4">
            <h5 class="fw-bold mb-4 border-bottom pb-2 text-primary"><i class="fas fa-id-card me-2"></i> Account Details</h5>
            
            <?php if($error): ?>
                <div class="alert alert-danger border-0 rounded-3 mb-4"><i class="fas fa-exclamation-circle me-2"></i> <?php echo $error; ?></div>
            <?php endif; ?>
            <?php if($success): ?>
                <div class="alert alert-success border-0 rounded-3 mb-4"><i class="fas fa-check-circle me-2"></i> <?php echo $success; ?></div>
            <?php endif; ?>

            <form method="POST">
                <div class="row">
                    <div class="col-md-6 mb-4">
                        <label class="form-label fw-semibold small">Full Name</label>
                        <input type="text" name="name" class="form-control form-control-lg bg-light" value="<?php echo htmlspecialchars($user['name']); ?>" required>
                    </div>
                    <div class="col-md-6 mb-4">
                        <label class="form-label fw-semibold small">User ID / Username</label>
                        <input type="text" name="username" class="form-control form-control-lg bg-light" value="<?php echo htmlspecialchars($user['username']); ?>" required>
                    </div>
                    <div class="col-md-6 mb-4">
                        <label class="form-label fw-semibold small">Email Address</label>
                        <input type="email" name="email" class="form-control form-control-lg bg-light" value="<?php echo htmlspecialchars($user['email']); ?>" required>
                    </div>
                    <div class="col-md-6 mb-4">
                        <label class="form-label fw-semibold small">Phone Number</label>
                        <input type="text" name="phone" class="form-control form-control-lg bg-light" value="<?php echo htmlspecialchars($user['phone']); ?>" required>
                    </div>
                    <div class="col-md-6 mb-4">
                        <label class="form-label fw-semibold small">Wallet Balance (₹)</label>
                        <input type="number" name="balance" step="0.01" class="form-control form-control-lg bg-light" value="<?php echo htmlspecialchars($user['balance']); ?>" required>
                    </div>
                    <div class="col-md-6 mb-4">
                        <label class="form-label fw-semibold small">Account Status</label>
                        <select name="status" class="form-select form-select-lg bg-light">
                            <option value="active" <?php echo $user['status'] === 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="blocked" <?php echo $user['status'] === 'blocked' ? 'selected' : ''; ?>>Blocked</option>
                        </select>
                    </div>
                </div>
                <button type="submit" name="update_details" class="btn btn-premium btn-lg px-5 py-3 shadow">
                    <i class="fas fa-save me-2"></i> Save Changes
                </button>
            </form>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="glass-card p-5 border-danger border-opacity-10">
            <h5 class="fw-bold mb-4 border-bottom pb-2 text-danger"><i class="fas fa-key me-2"></i> Reset Password</h5>
            <form method="POST">
                <div class="mb-4">
                    <label class="form-label fw-semibold small text-muted">New Password</label>
                    <input type="password" name="new_password" class="form-control bg-light" placeholder="••••••••" required>
                </div>
                <div class="mb-4">
                    <label class="form-label fw-semibold small text-muted">Confirm Password</label>
                    <input type="password" name="confirm_password" class="form-control bg-light" placeholder="••••••••" required>
                </div>
                <button type="submit" name="change_password" class="btn btn-outline-danger w-100 py-3 fw-bold rounded-pill">
                    <i class="fas fa-sync-alt me-2"></i> Update Password
                </button>
            </form>
            <div class="mt-4 p-3 bg-danger bg-opacity-10 rounded-4 text-center">
                <p class="small text-danger mb-0"><i class="fas fa-exclamation-triangle me-1"></i> Admin can reset any user's password without knowing the old one.</p>
            </div>
        </div>
    </div>
</div>

<?php include '../includes/footer.php'; ?>
