<?php
require '../includes/db.php';
require '../includes/functions.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// PAGINATION
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $limit;

// SEARCH
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';

// ==========================
// HANDLE ACTIONS
// ==========================

// APPROVE
if (isset($_GET['approve'])) {

    $user_id = (int)$_GET['approve'];

    $bill = mysqli_query($conn,"
        SELECT * FROM billings 
        WHERE user_id='$user_id' 
        ORDER BY id DESC LIMIT 1
    ");

    $b = mysqli_fetch_assoc($bill);

    $amount = (float)($b['amount'] ?? 0);
    $bill_id = $b['id'] ?? 0;

    mysqli_query($conn,"
        UPDATE users 
        SET payment_status=1,
            balance = balance + $amount
        WHERE id='$user_id'
    ");

    if ($bill_id) {
        mysqli_query($conn,"
            UPDATE billings 
            SET status='approved' 
            WHERE id='$bill_id'
        ");
    }

    header("Location: users.php?page=$page&success=approved");
    exit;
}

// DELETE
if (isset($_GET['delete'])) {

    $user_id = (int)$_GET['delete'];

    mysqli_query($conn,"DELETE FROM billings WHERE user_id='$user_id'");
    mysqli_query($conn,"
        DELETE FROM messages 
        WHERE sender_id='$user_id' OR receiver_id='$user_id'
    ");
    mysqli_query($conn,"DELETE FROM users WHERE id='$user_id'");

    header("Location: users.php?page=$page&success=deleted");
    exit;
}

// ==========================
// BILLING
// ==========================

$successMsg = "";

if (isset($_POST['bill'])) {

    $user_id = (int)$_POST['user_id'];
    $amount = (float)$_POST['amount'];
    $desc = mysqli_real_escape_string($conn, $_POST['desc']);

    $checkUser = mysqli_query($conn,"
        SELECT id, currency FROM users WHERE id='$user_id' LIMIT 1
    ");

    if (mysqli_num_rows($checkUser) == 0) {
        $successMsg = "Invalid user selected.";
    } else {

        $userData = mysqli_fetch_assoc($checkUser);
        $currency = $userData['currency'] ?? 'USD';

        $btc_usd_rate = 65000;
        $usd_value = $amount * $btc_usd_rate;

        $rateRes = @json_decode(file_get_contents("https://open.er-api.com/v6/latest/USD"), true);
        $rate = $rateRes['rates'][$currency] ?? 1;

        $fiat_amount = $usd_value * $rate;

        mysqli_query($conn,"
            INSERT INTO billings 
            (user_id, amount, fiat_amount, fiat_currency, description) 
            VALUES 
            ('$user_id','$amount','$fiat_amount','$currency','$desc')
        ");

        $successMsg = "Billing assigned to User ID: $user_id";
    }
}

// ==========================
// LOAD UI
// ==========================

include 'includes/header.php';
include 'includes/sidebar.php';

// TOTAL USERS
$totalRes = mysqli_query($conn,"SELECT COUNT(*) as total FROM users");
$totalUsers = mysqli_fetch_assoc($totalRes)['total'];
$totalPages = ceil($totalUsers / $limit);

// FETCH USERS (WITH SEARCH)
if (!empty($search)) {

    $res = mysqli_query($conn,"
        SELECT u.*, ue.phone
        FROM users u
        LEFT JOIN user_emails ue 
            ON ue.email = u.email
        WHERE 
            u.email LIKE '%$search%' OR
            ue.phone LIKE '%$search%' OR
            u.customer_id LIKE '%$search%'
        ORDER BY u.id DESC
        LIMIT $start, $limit
    ");

} else {

    $res = mysqli_query($conn,"
        SELECT u.*, ue.phone
        FROM users u
        LEFT JOIN user_emails ue 
            ON ue.email = u.email
        ORDER BY u.id DESC
        LIMIT $start, $limit
    ");
}
?>

<div class="row">
<div class="col-xl-8 col-lg-11 mx-auto">

<div class="card p-3">

<!-- SUCCESS -->
<?php if(isset($_GET['success'])): ?>
<div class="alert alert-success">
    <?php 
    if($_GET['success']=='approved') echo "User approved & balance updated";
    if($_GET['success']=='deleted') echo "User deleted";
    ?>
</div>
<?php endif; ?>

<?php if(!empty($successMsg)): ?>
<div class="alert alert-info"><?php echo $successMsg; ?></div>
<?php endif; ?>

<!-- HEADER -->
<div class="d-flex justify-content-between mb-3">
    <h4 class="text-primary">Users</h4>
</div>

<!-- SEARCH -->
<form method="GET" class="mb-3 d-flex gap-2">
    <input type="text" name="search" class="form-control"
           placeholder="Search email, phone, customer ID..."
           value="<?php echo $_GET['search'] ?? ''; ?>">

    <button class="btn btn-primary">Search</button>
</form>

<!-- TABLE -->
<div class="table-responsive">
<table class="table table-dark table-hover">

<thead>
<tr>
    <th>Email</th>
    <th>Phone</th>
    <th>Currency</th>
    <th>Customer ID</th>
    <th>Status</th>
    <th>Action</th>
</tr>
</thead>

<tbody>

<?php while($u = mysqli_fetch_assoc($res)): ?>
<tr>

<td><?php echo $u['email'] ?? 'No Email'; ?></td>
<td><?php echo !empty($u['phone']) ? $u['phone'] : 'N/A'; ?></td>

<td>
<span class="badge bg-secondary">
<?php echo $u['currency']; ?>
</span>
</td>

<td><?php echo $u['customer_id']; ?></td>

<td>
<?php if($u['payment_status']): ?>
<span class="badge bg-success">Active</span>
<?php else: ?>
<span class="badge bg-warning text-dark">Pending</span>
<?php endif; ?>
</td>

<td>

<div class="d-flex gap-2 mb-2">

<a href="?approve=<?php echo $u['id']; ?>&page=<?php echo $page; ?>" 
   class="btn btn-sm btn-success">
   Approve
</a>

<a href="?delete=<?php echo $u['id']; ?>&page=<?php echo $page; ?>" 
   onclick="return confirm('Delete user?')" 
   class="btn btn-sm btn-danger">
   Delete
</a>

</div>

<form method="POST" class="d-flex gap-2 flex-wrap">

<input type="hidden" name="user_id" value="<?php echo $u['id']; ?>">

<input type="number" name="amount" class="form-control form-control-sm"
       placeholder="BTC amount" step="0.00000001" required>

<input type="text" name="desc" class="form-control form-control-sm"
       placeholder="Reason" required>

<button name="bill" class="btn btn-sm btn-primary">
Bill
</button>

</form>

</td>
</tr>
<?php endwhile; ?>

</tbody>
</table>
</div>

<!-- PAGINATION -->
<ul class="pagination justify-content-center mt-3">

<li class="page-item <?php if($page<=1) echo 'disabled'; ?>">
<a class="page-link" href="?page=<?php echo $page-1; ?>&search=<?php echo $search; ?>">Prev</a>
</li>

<?php for($i=1;$i<=$totalPages;$i++): ?>
<li class="page-item <?php if($i==$page) echo 'active'; ?>">
<a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo $search; ?>">
<?php echo $i; ?>
</a>
</li>
<?php endfor; ?>

<li class="page-item <?php if($page>=$totalPages) echo 'disabled'; ?>">
<a class="page-link" href="?page=<?php echo $page+1; ?>&search=<?php echo $search; ?>">Next</a>
</li>

</ul>

</div>
</div>
</div>

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