<?php
include 'admin-header.php';
require_once '../includes/helpers.php';

// --- 1. VALIDATE USER ID & FETCH USER DATA ---

// Get user ID from URL and validate it
$user_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$user_id) {
    $_SESSION['error_message'] = "Invalid user ID.";
    header("Location: manage-users.php");
    exit();
}

// --- 2. HANDLE FORM SUBMISSION (UPDATE LOGIC) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Ensure the submitted user_id matches the one in the URL
    if ($_POST['user_id'] != $user_id) {
        $_SESSION['error_message'] = "Mismatched user ID.";
        header("Location: manage-users.php");
        exit();
    }

    // Sanitize and retrieve form data
    $full_name = trim($_POST['full_name']);
    $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
    $role = $_POST['role'] ?? 'customer';
    $status = $_POST['status'] ?? 'active';
    $verification_status = $_POST['verification_status'] ?? null;
    $wallet_balance = filter_input(INPUT_POST, 'wallet_balance', FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);

    // Basic validation
    if (empty($full_name) || !$email) {
        $_SESSION['error_message'] = "Please provide a valid full name and email address.";
    } else {
        // Update user's main details
        $sql = "UPDATE users SET full_name = ?, email = ?, role = ?, status = ?, verification_status = ?, wallet_balance = ? WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sssssdi", $full_name, $email, $role, $status, $verification_status, $wallet_balance, $user_id);
        
        if ($stmt->execute()) {
            $_SESSION['success_message'] = "User details updated successfully.";
        } else {
            $_SESSION['error_message'] = "Failed to update user details.";
        }
        $stmt->close();

        // Handle password reset if a new password was entered
        $new_password = $_POST['new_password'];
        if (!empty($new_password)) {
            $password_hash = password_hash($new_password, PASSWORD_DEFAULT);
            $stmt_pass = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
            $stmt_pass->bind_param("si", $password_hash, $user_id);
            if ($stmt_pass->execute()) {
                 $_SESSION['success_message'] .= " Password has been updated.";
            }
            $stmt_pass->close();
        }

        header("Location: manage-users.php");
        exit();
    }
}

// --- 3. FETCH USER DATA TO PRE-POPULATE THE FORM ---
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ? AND role != 'admin'");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
$stmt->close();

// If no user is found, redirect back
if (!$user) {
    $_SESSION['error_message'] = "User not found.";
    header("Location: manage-users.php");
    exit();
}

?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <div>
        <h1 class="h2">Edit User</h1>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="manage-users.php">Users</a></li>
                <li class="breadcrumb-item active" aria-current="page"><?php echo htmlspecialchars($user['full_name']); ?></li>
            </ol>
        </nav>
    </div>
</div>

<div class="card shadow-sm">
    <div class="card-header">
        <h5 class="mb-0">Editing Profile for <span class="text-primary"><?php echo htmlspecialchars($user['full_name']); ?></span></h5>
    </div>
    <div class="card-body">
        <form action="edit-user.php?id=<?php echo $user_id; ?>" method="POST">
            <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
            <div class="row g-4">
                <div class="col-md-6">
                    <h5 class="mb-3">Account Information</h5>
                    <div class="mb-3">
                        <label for="full_name" class="form-label">Full Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="full_name" name="full_name" value="<?php echo htmlspecialchars($user['full_name']); ?>" required>
                    </div>
                    <div class="mb-3">
                        <label for="email" class="form-label">Email Address <span class="text-danger">*</span></label>
                        <input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" required>
                    </div>
                    <div class="mb-3">
                        <label for="role" class="form-label">Role</label>
                        <select class="form-select" id="role" name="role">
                            <option value="customer" <?php if($user['role'] == 'customer') echo 'selected'; ?>>Customer</option>
                            <option value="tour_partner" <?php if($user['role'] == 'tour_partner') echo 'selected'; ?>>Tour Partner</option>
                            <option value="hotel_partner" <?php if($user['role'] == 'hotel_partner') echo 'selected'; ?>>Hotel Partner</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="wallet_balance" class="form-label">Wallet Balance</label>
                        <div class="input-group">
                            <span class="input-group-text">₱</span>
                            <input type="number" step="0.01" class="form-control" id="wallet_balance" name="wallet_balance" value="<?php echo number_format($user['wallet_balance'] ?? 0, 2); ?>">
                        </div>
                    </div>
                </div>

                <div class="col-md-6">
                    <h5 class="mb-3">Administrative Controls</h5>
                    <div class="mb-3">
                        <label for="status" class="form-label">Account Status</label>
                        <select class="form-select" id="status" name="status">
                            <option value="active" <?php if($user['status'] == 'active') echo 'selected'; ?>>Active</option>
                            <option value="suspended" <?php if($user['status'] == 'suspended') echo 'selected'; ?>>Suspended</option>
                        </select>
                    </div>

                    <?php if (str_contains($user['role'], '_partner')): ?>
                    <div class="mb-3">
                        <label for="verification_status" class="form-label">Partner Verification Status</label>
                        <select class="form-select" id="verification_status" name="verification_status">
                            <option value="pending" <?php if($user['verification_status'] == 'pending') echo 'selected'; ?>>Pending</option>
                            <option value="verified" <?php if($user['verification_status'] == 'verified') echo 'selected'; ?>>Verified</option>
                            <option value="rejected" <?php if($user['verification_status'] == 'rejected') echo 'selected'; ?>>Rejected</option>
                        </select>
                    </div>
                    <?php endif; ?>

                    <div class="mb-3">
                         <label for="new_password" class="form-label">Reset Password</label>
                         <input type="password" class="form-control" id="new_password" name="new_password" placeholder="Leave blank to keep current password">
                    </div>
                </div>
            </div>

            <hr class="my-4">

            <div class="d-flex justify-content-end gap-2">
                <a href="manage-users.php" class="btn btn-secondary">Cancel</a>
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-check-circle-fill me-1"></i> Save Changes
                </button>
            </div>
        </form>
    </div>
</div>

<?php include 'admin-footer.php'; ?>
