<?php
session_start();
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 1) {
    header("Location: ../../index.php");
    exit();
}

include('../../includes/config.php');
include('../../includes/header.php');
include('../../includes/footer.php');

$id = (int)($_GET['id'] ?? 0);
$user = $conn->query("SELECT * FROM users WHERE id = $id")->fetch_assoc();
$roles = $conn->query("SELECT * FROM roles")->fetch_all(MYSQLI_ASSOC);
$stores = $conn->query("SELECT * FROM stores")->fetch_all(MYSQLI_ASSOC);

if (!$user) {
    echo "User not found.";
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit User - Digital POS</title>
    <style>
        body, html {
            margin: 0; padding: 0;
            font-family: 'Segoe UI', sans-serif;
            background: url('../../images/profile.jpg') no-repeat center center fixed;
            background-size: cover;
            color: white;
            min-height: 100vh;
        }
        .overlay {
            position: fixed;
            top: 0; left: 0;
            width: 100%; height: 100%;
            background: rgba(0,0,0,0.6);
            z-index: -1;
        }
        .form-container {
            max-width: 600px;
            margin: 90px auto 50px auto;
            background: rgba(255,255,255,0.08);
            backdrop-filter: blur(12px);
            border-radius: 20px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.6);
            padding: 30px 40px;
        }
        h2 {
            text-align: center;
            margin-bottom: 30px;
            color: #fff;
        }
        label {
            display: block;
            margin-top: 15px;
            font-weight: 600;
            color: #eee;
        }
        input, select {
            width: 100%;
            padding: 12px;
            margin-top: 6px;
            border-radius: 12px;
            border: none;
            background: rgba(255,255,255,0.2);
            color: white;
            font-size: 1rem;
        }
        input::placeholder {
            color: #ccc;
        }
        button {
            margin-top: 30px;
            width: 100%;
            padding: 14px;
            border: none;
            border-radius: 25px;
            background-color: #ff6f00;
            color: white;
            font-weight: 700;
            font-size: 1.1rem;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        button:hover {
            background-color: #e65c00;
        }
        .success-message {
            background: #2e7d32cc; /* semi-transparent green */
            border-radius: 12px;
            padding: 12px 20px;
            margin-bottom: 20px;
            color: #d0f0c0;
            font-weight: 600;
            text-align: center;
        }
        @media (max-width: 700px) {
            .form-container {
                width: 90%;
                margin: 80px auto 30px auto;
                padding: 25px 20px;
            }
            label, input, select, button {
                font-size: 0.95rem;
            }
        }
    </style>
</head>
<body>

<div class="overlay"></div>

<div class="form-container">
    <h2>Edit User</h2>

    <?php if (isset($_GET['updated']) && $_GET['updated'] == 1): ?>
        <div class="success-message">✅ User updated successfully.</div>
    <?php endif; ?>

    <form method="POST" id="editUserForm">
        <input type="hidden" name="id" value="<?= htmlspecialchars($user['id']) ?>">
        
        <label>First Name</label>
        <input type="text" name="first_name" value="<?= htmlspecialchars($user['first_name']) ?>" required>

        <label>Last Name</label>
        <input type="text" name="last_name" value="<?= htmlspecialchars($user['last_name']) ?>" required>

        <label>Username</label>
        <input type="text" name="username" value="<?= htmlspecialchars($user['username']) ?>" required>

        <label>Email</label>
        <input type="email" name="email" value="<?= htmlspecialchars($user['email']) ?>" required>

        <label>Phone Number</label>
        <input type="text" name="phone_number" value="<?= htmlspecialchars($user['phone_number']) ?>">

        <label>Role</label>
        <select name="role_id" required>
            <?php foreach ($roles as $role): ?>
                <option value="<?= $role['id'] ?>" <?= $user['role_id'] == $role['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($role['role_name']) ?>
                </option>
            <?php endforeach; ?>
        </select>

        <label>Store</label>
        <select name="store_id" required>
            <?php foreach ($stores as $store): ?>
                <option value="<?= $store['id'] ?>" <?= $user['store_id'] == $store['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($store['store_name']) ?>
                </option>
            <?php endforeach; ?>
        </select>

        <label>Password (leave blank to keep current)</label>
        <input type="password" name="password" placeholder="••••••••••••">

        <button type="submit">Update User</button>
    </form>
</div>

<script>
document.getElementById('editUserForm').addEventListener('submit', function(e) {
    e.preventDefault();

    const form = this;
    const formData = new FormData(form);
    const submitBtn = form.querySelector('button[type="submit"]');
    const userId = formData.get('id');

    submitBtn.disabled = true;
    submitBtn.textContent = 'Updating...';

    fetch('update_user.php', {
        method: 'POST',
        body: formData
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            window.location.href = 'edit_user.php?id=' + userId + '&updated=1';
        } else {
            alert('❌ Error: ' + data.message);
        }
    })
    .catch(err => {
        console.error('Update failed:', err);
        alert('❌ Network error occurred.');
    })
    .finally(() => {
        submitBtn.disabled = false;
        submitBtn.textContent = 'Update User';
    });
});
</script>

</body>
</html>
