<?php
$page_title = "ইউজার এডিট";
require_once 'includes/auth_check.php'; // This file now contains the log_activity function

// Check if user ID is provided and is valid
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("location: users.php");
    exit;
}

$user_id = (int)$_GET['id'];
$admin_id = (int)$_SESSION['admin_id'];
$message = '';

// Handle Form Submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // ======== Handle Profile Information Update ========
    if (isset($_POST['update_profile'])) {
        $full_name = trim($_POST['full_name']);
        $level_id = (int)$_POST['level_id'];
        $status = $_POST['status'];

        if (empty($full_name) || empty($level_id) || empty($status)) {
            $message = '<div class="alert alert-danger">প্রোফাইলের সকল তথ্য পূরণ করুন।</div>';
        } else {
            $stmt = $conn->prepare("UPDATE users SET full_name=?, level_id=?, status=? WHERE id=?");
            $stmt->bind_param("sisi", $full_name, $level_id, $status, $user_id);
            
            if ($stmt->execute()) {
                $message = '<div class="alert alert-success">প্রোফাইল সফলভাবে আপডেট হয়েছে।</div>';
                
                // Log this activity
                $log_details = "User ID: $user_id | Name: $full_name | Level ID: $level_id | Status: $status";
                log_activity($conn, $admin_id, 'Updated User Profile', $log_details);

            } else {
                $message = '<div class="alert alert-danger">প্রোফাইল আপডেট ব্যর্থ হয়েছে।</div>';
            }
            $stmt->close();
        }
    }

    // ======== Handle Balance Update ========
    if (isset($_POST['update_balance'])) {
        $action = $_POST['action'];
        $amount = (float)$_POST['amount'];
        $reason = trim($_POST['reason']);

        if ($amount > 0 && !empty($reason)) {
            $conn->begin_transaction();
            try {
                $user_res = $conn->query("SELECT balance FROM users WHERE id=$user_id FOR UPDATE")->fetch_assoc();
                $current_balance = $user_res['balance'];

                if ($action == 'deduct' && $amount > $current_balance) {
                    throw new Exception("কাটার জন্য পর্যাপ্ত ব্যালেন্স নেই।");
                }

                $operator = ($action == 'add') ? '+' : '-';
                $conn->query("UPDATE users SET balance = balance $operator $amount WHERE id = $user_id");

                $type = ($action == 'add') ? 'Admin Deposit' : 'Admin Withdraw';
                $stmt = $conn->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, ?, ?, ?)");
                $stmt->bind_param("isds", $user_id, $type, $amount, $reason);
                $stmt->execute();
                
                // Log this activity before committing
                $log_details = "User ID: $user_id | Action: $action | Amount: $amount | Reason: $reason";
                log_activity($conn, $admin_id, 'Updated User Balance', $log_details);

                $conn->commit();
                $message = '<div class="alert alert-success">ব্যালেন্স সফলভাবে আপডেট হয়েছে।</div>';

            } catch (Exception $e) {
                $conn->rollback();
                $message = '<div class="alert alert-danger">ব্যালেন্স আপডেট ব্যর্থ: ' . $e->getMessage() . '</div>';
            }
        } else {
             $message = '<div class="alert alert-danger">ব্যালেন্স আপডেটের জন্য পরিমাণ এবং কারণ উল্লেখ করুন।</div>';
        }
    }
}

// Fetch user data to display in the form
$user_stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$user_stmt->bind_param("i", $user_id);
$user_stmt->execute();
$user_result = $user_stmt->get_result();
if ($user_result->num_rows === 0) {
    header("location: users.php");
    exit;
}
$user = $user_result->fetch_assoc();
$user_stmt->close();

// Fetch all reseller levels for the dropdown
$levels_result = $conn->query("SELECT id, level_name FROM reseller_levels ORDER BY rank ASC");


include 'includes/header.php';
?>

<div class="container-fluid">
    <a href="users.php" class="btn btn-secondary mb-3"><i class="fas fa-arrow-left"></i> সকল ইউজারে ফিরে যান</a>
    <h2>ইউজার এডিট: <?php echo htmlspecialchars($user['full_name']); ?></h2>
    
    <?php if(!empty($message)) echo $message; ?>

    <div class="row mt-4">
        <div class="col-md-6 mb-4">
            <div class="card h-100">
                <div class="card-header"><h4>প্রোফাইল তথ্য</h4></div>
                <div class="card-body">
                    <form method="POST" action="">
                        <div class="mb-3">
                            <label class="form-label">সম্পূর্ণ নাম</label>
                            <input type="text" name="full_name" class="form-control" value="<?php echo htmlspecialchars($user['full_name']); ?>" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">মোবাইল নম্বর (পরিবর্তনযোগ্য নয়)</label>
                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($user['mobile']); ?>" disabled>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">ইউজার লেভেল</label>
                            <select name="level_id" class="form-select" required>
                                <?php while($level = $levels_result->fetch_assoc()): ?>
                                    <option value="<?php echo $level['id']; ?>" <?php if ($user['level_id'] == $level['id']) echo 'selected'; ?>>
                                        <?php echo htmlspecialchars($level['level_name']); ?>
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">স্ট্যাটাস</label>
                            <select name="status" class="form-select" required>
                                <option value="Active" <?php if ($user['status'] == 'Active') echo 'selected'; ?>>Active</option>
                                <option value="Inactive" <?php if ($user['status'] == 'Inactive') echo 'selected'; ?>>Inactive</option>
                            </select>
                        </div>
                        <button type="submit" name="update_profile" class="btn btn-primary">আপডেট প্রোফাইল</button>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-md-6 mb-4">
            <div class="card h-100">
                <div class="card-header"><h4>ব্যালেন্স ম্যানেজমেন্ট</h4></div>
                <div class="card-body">
                    <h5>বর্তমান ব্যালেন্স: ৳<?php echo number_format($user['balance'], 2); ?></h5>
                    <hr>
                    <form method="POST" action="">
                        <div class="mb-3">
                            <label class="form-label">একশন</label>
                            <select name="action" class="form-select">
                                <option value="add">ব্যালেন্স যোগ করুন</option>
                                <option value="deduct">ব্যালেন্স কাটুন</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">পরিমাণ</label>
                            <input type="number" step="0.01" name="amount" class="form-control" placeholder="0.00" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">কারণ</label>
                            <input type="text" name="reason" class="form-control" placeholder="যেমন: Refund for failed recharge" required>
                        </div>
                        <button type="submit" name="update_balance" class="btn btn-success">আপডেট ব্যালেন্স</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
include 'includes/footer.php';
$conn->close();
?>