<?php
ob_start();
// 1. Session & Auth Control
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit(); }

require_once('../titancore/titanconfig.php');

/** * ★ SESSION KEY FIX ★
 */
$utype = $_SESSION['utype'] ?? $_SESSION['user_type'] ?? 'Retailer';
$uid = $_SESSION['user_id'];
$u_name = $_SESSION['user_name'] ?? 'User';

// 2. Retailer Security Check
if ($utype == 'Retailer') {
    echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
    <script>
        window.onload = function() {
            Swal.fire({
                title: 'Access Denied!',
                text: 'Retailers cannot transfer balance.',
                icon: 'error',
                confirmButtonColor: '#2c7be5'
            }).then(() => { window.location.href = 'titanhome.php'; });
        };
    </script>";
    exit();
}

require_once('../titancore/titanheader.php');

$swal_msg = "";

// Fetch Site Settings for CRM Header
$site_query = $conn->query("SELECT site_name FROM settings WHERE id = 1");
$site_data = $site_query->fetch_assoc();
$display_name = $site_data['site_name'] ?? 'ApiNexus';

// 3. Handle Transfer Logic
if (isset($_POST['transfer_btn'])) {
    $receiver_id = mysqli_real_escape_string($conn, $_POST['receiver_id']);
    $amount = floatval(mysqli_real_escape_string($conn, $_POST['amount']));

    if ($amount <= 0) {
        $swal_msg = "Swal.fire('Error', 'Please enter a valid amount', 'error');";
    } else {
        // Sender balance check
        $sender = $conn->query("SELECT wallet FROM users WHERE id = '$uid'")->fetch_assoc();
        
        if ($utype != 'TitanAdmin' && $sender['wallet'] < $amount) {
            $swal_msg = "Swal.fire('Low Balance', 'Insufficient wallet balance', 'warning');";
        } else {
            // Transaction Start
            $conn->begin_transaction();
            try {
                // 1. Update Receiver
                $conn->query("UPDATE users SET wallet = wallet + $amount WHERE id = '$receiver_id'");
                
                // 2. Update Sender (If not Admin)
                if ($utype != 'TitanAdmin') {
                    $conn->query("UPDATE users SET wallet = wallet - $amount WHERE id = '$uid'");
                }
                
                // Transaction Commit
                $conn->commit();
                $swal_msg = "Swal.fire('Success', '₹$amount Transferred Successfully', 'success').then(() => { window.location.href='balance_transfer.php'; });";
            } catch (Exception $e) {
                $conn->rollback();
                $swal_msg = "Swal.fire('Failed', 'Transaction Error', 'error');";
            }
        }
    }
}

// ---------------- SEARCH & PAGINATION LOGIC START ----------------
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, trim($_GET['search'])) : '';

// Base Condition based on user role
if ($utype == 'TitanAdmin') {
    $base_filter = "id != '$uid'";
} else {
    $base_filter = "referred_by = '$uid'";
}

// Global query matching for dropdown select lists (changed 'mobile' to 'phone')
$dropdown_list = $conn->query("SELECT id, name, phone, shop_name, wallet, user_type FROM users WHERE $base_filter ORDER BY name ASC");

// Append search query parameters if exists (changed 'mobile' to 'phone')
if (!empty($search)) {
    $base_filter .= " AND (name LIKE '%$search%' OR shop_name LIKE '%$search%' OR id LIKE '%$search%' OR user_type LIKE '%$search%' OR phone LIKE '%$search%')";
}

// Pagination configurations
$limit = 15; 
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) { $page = 1; }
$offset = ($page - 1) * $limit;

// Calculate Total Records matching filters
$count_query = "SELECT COUNT(*) AS total FROM users WHERE $base_filter";
$count_res = $conn->query($count_query);
$total_records = 0;
if ($count_res && $row_count = $count_res->fetch_assoc()) {
    $total_records = $row_count['total'];
}

// Adjust valid pages index
$total_pages = ceil($total_records / $limit);
if ($page > $total_pages && $total_pages > 0) { 
    $page = $total_pages; 
    $offset = ($page - 1) * $limit; 
}

// Final Dynamic Paginated Query for Overview Grid (changed 'mobile' to 'phone')
$table_list = $conn->query("SELECT id, name, phone, shop_name, wallet, user_type FROM users WHERE $base_filter ORDER BY id DESC LIMIT $limit OFFSET $offset");

$start_entry = $total_records == 0 ? 0 : $offset + 1;
$end_entry = min($offset + $limit, $total_records);
// ---------------- SEARCH & PAGINATION LOGIC END ----------------
?>

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" />

<div class="row mb-3">
    <div class="col">
        <div class="card bg-100 shadow-none border">
            <div class="row gx-0 flex-between-center p-3">
                <div class="col-sm-auto d-flex align-items-center">
                    <img class="ms-n2" src="../assets/img/illustrations/crm-bar-chart.png" alt="" width="90" />
                    <div>
                        <h6 class="text-primary fs-10 mb-0">Welcome back, <?php echo htmlspecialchars($u_name); ?></h6>
                        <h4 class="text-primary fw-bold mb-0"><?php echo htmlspecialchars($display_name); ?> <span class="text-info fw-medium">Wallet</span></h4>
                    </div>
                </div>
                <div class="col-md-auto">
                    <div class="form-control form-control-sm bg-white border-200">
                        <span class="fas fa-calendar-day text-primary me-2"></span>
                        <span class="fw-bold text-primary"><?php echo date('d M, Y'); ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card mb-3">
    <div class="card-header bg-light">
        <h5 class="mb-0 text-primary fw-bold"><i class="fas fa-exchange-alt me-2"></i>Wallet Balance Transfer</h5>
        <p class="mb-0 fs-11">Send funds instantly to your team members' wallets.</p>
    </div>
    <div class="card-body bg-body-tertiary">
        <form method="POST" class="row g-3 justify-content-center">
            <div class="col-md-5">
                <label class="form-label fw-bold">Select User (Receiver)</label>
                <select class="form-select select2 shadow-none" name="receiver_id" required>
                    <option value="">Search by Name or Number...</option>
                    <?php if($dropdown_list && $dropdown_list->num_rows > 0): ?>
                    <?php while($row = $dropdown_list->fetch_assoc()): ?>
                        <option value="<?php echo $row['id']; ?>">
                            <?php echo htmlspecialchars($row['name']); ?> - <?php echo htmlspecialchars($row['phone']); ?> (<?php echo htmlspecialchars($row['shop_name']); ?>) | Bal: ₹<?php echo number_format($row['wallet'], 2); ?>
                        </option>
                    <?php endwhile; ?>
                    <?php endif; ?>
                </select>
            </div>
            
            <div class="col-md-4">
                <label class="form-label fw-bold">Amount (₹)</label>
                <div class="input-group">
                    <span class="input-group-text bg-primary text-white border-end-0">₹</span>
                    <input class="form-control shadow-none border-start-0" name="amount" type="number" step="0.01" placeholder="0.00" required />
                </div>
            </div>

            <div class="col-md-3 align-self-end">
                <button class="btn btn-primary w-100 fw-bold shadow-none" name="transfer_btn" type="submit">
                    <i class="fas fa-paper-plane me-2"></i> Transfer Now
                </button>
            </div>
        </form>
    </div>
</div>

<div class="card mb-3">
    <div class="card-header bg-light border-bottom d-flex flex-column flex-sm-row justify-content-between align-items-sm-center gap-2 py-2">
        <h6 class="mb-0 text-700"><i class="fas fa-users-cog me-2"></i>Team Wallet Overview</h6>
       
               
            </div>
        </form>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive scrollbar">
            <table class="table table-sm table-striped table-hover fs-10 mb-0">
                <thead class="bg-200 text-900">
                    <tr>
                        <th class="ps-3 align-middle">Member Details</th>
                        <th class="align-middle">Role</th>
                        <th class="text-end pe-3 align-middle">Current Wallet Balance</th>
                    </tr>
                </thead>
                <tbody class="list">
                    <?php if($table_list && $table_list->num_rows > 0): ?>
                        <?php while($row = $table_list->fetch_assoc()): ?>
                        <tr>
                            <td class="ps-3 py-2 align-middle">
                                <div class="fw-bold text-primary"><?php echo htmlspecialchars($row['name']); ?></div>
                                <div class="fs-11 text-700"><i class="fas fa-phone-alt me-1 text-500"></i><?php echo htmlspecialchars($row['phone']); ?></div>
                                <div class="fs-11 text-500"><?php echo htmlspecialchars($row['shop_name']); ?></div>
                            </td>
                            <td class="align-middle">
                                <span class="badge badge-subtle-secondary fw-semi-bold"><?php echo htmlspecialchars($row['user_type']); ?></span>
                            </td>
                            <td class="text-end pe-3 align-middle fw-bold text-success">
                                ₹<?php echo number_format($row['wallet'], 2); ?>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr><td colspan="3" class="text-center py-4 text-500 fst-italic">No dynamic matching team records or users found.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="card-footer d-flex align-items-center justify-content-between py-2 border-top bg-100">
        <p class="mb-0 fs-10 text-700 fw-semi-bold">
            Showing <?php echo $start_entry; ?> to <?php echo $end_entry; ?> of <?php echo $total_records; ?> entries
        </p>
        <?php if ($total_pages > 1): ?>
        <nav aria-label="Page navigation">
            <ul class="pagination pagination-sm mb-0">
                <li class="page-item <?php echo ($page <= 1) ? 'disabled' : ''; ?>">
                    <a class="page-link shadow-none" href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
                
                <?php 
                $start_loop = max(1, $page - 2);
                $end_loop = min($total_pages, $page + 2);
                for ($i = $start_loop; $i <= $end_loop; $i++): 
                ?>
                    <li class="page-item <?php echo ($page == $i) ? 'active' : ''; ?>">
                        <a class="page-link shadow-none" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>"><?php echo $i; ?></a>
                    </li>
                <?php endfor; ?>

                <li class="page-item <?php echo ($page >= $total_pages) ? 'disabled' : ''; ?>">
                    <a class="page-link shadow-none" href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
            </ul>
        </nav>
        <?php endif; ?>
    </div>
    </div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
    // Initialize Searchable Dropdown
    $(document).ready(function() {
        $('.select2').select2({
            theme: 'bootstrap-5',
            width: '100%',
            placeholder: 'Search by Number, Name or Shop...'
        });
    });

    // Handle SweetAlert
    <?php echo $swal_msg; ?>
</script>

<?php 
require_once('../titancore/TitanFooter.php'); 
ob_end_flush();
?>