<?php
    $agents = $db->run("SELECT user.id, user.name, auth_token.consumedBy, auth_token.ua, auth_token.expiresAt, auth_token.consumedAt FROM `auth_token`, user WHERE ua IS NOT NULL AND consumedBy IS NOT NULL AND user.clientId != 0 AND user.id = `auth_token`.consumedBy GROUP BY name, ua ORDER BY name DESC");

    $userAgents = array_column($agents, 'ua');
    $counts = [];
    foreach ( $userAgents as $ua ) {
        $counts[$ua]++;
    }

    $labels = "'";
    $labels .= implode("','", array_unique($userAgents));
    $labels .= "'";

    $deviceData = implode(',', $counts);

    $tabs = [];
    $tabStrings = array_unique($userAgents);
    foreach ( $tabStrings as $tabString ) {
        $tabs[$tabString]['ua'] = $tabString;
        $tabs[$tabString]['clients'] = $db->run("SELECT DISTINCT user.name FROM `auth_token`, user WHERE auth_token.ua = ? AND auth_token.consumedBy IS NOT NULL AND user.clientId != 0 AND user.id = `auth_token`.consumedBy", $tabString);
    }
?>
<!-- <pre> -->
    <?php // print_r($counts); ?>
<!-- </pre> -->

<div id="deviceModal" class="modal" tabindex="-1">
    <div class="modal-dialog modal-dialog-scrollable modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <div class="d-block">
                    <h5 id="deviceModalTitle" class="modal-title">Client Devices</h5>
                    <!-- <small class="text-muted">Showing last 100 actions</small> -->
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div id="deviceModalBody" class="modal-body px-0">

            <ul class="nav nav-tabs border-bottom-0 flex-nowrap overflow-x-scroll overflow-y-hidden align-items-center" id="tablist" role="tablist">
    <?php
        $i = 0; 
        foreach ( $tabs as $tab ) :
            
    ?>
    <li class="nav-item" role="presentation">
        <button class="nav-link" id="<?php echo $tab['ua']; ?>-tab" data-bs-toggle="tab" data-bs-target="#<?php echo $tab['ua']; ?>-tab-pane" type="button" role="tab" aria-controls="<?php echo $tab['ua']; ?>-tab-pane">
            <span class="badge rounded-pill <?php echo $class; ?> text-end py-2"><?php echo $tab['ua']; ?> (<?php echo $counts[$tab['ua']]; ?>)</span>
        </button>
    </li>
    <?php 
            $i++;
        endforeach; 
    ?>
    <!-- <li class="nav-item text-muted text-nowrap ms-auto">(# tasks - % complete)</li> -->
</ul>
<div class="tab-content" id="tabcontent">
    <?php 
        $i = 0;
        foreach ( $tabs as $tab ) :
            // $statusString = str_replace(' ', '-', $status);
    ?>
    <div class="tab-pane fade" id="<?php echo $tab['ua']; ?>-tab-pane" role="tabpanel" aria-labelledby="<?php echo $tab['ua']; ?>-tab" tabindex="0">
        <ul class="list-group">
        <?php
            $i = 1;
            foreach ( $tab['clients'] as $client ) : 
        ?>
            <li class="list-group-item d-flex justify-content-between align-items-center">
                <div class="fw-bold flex-nowrap text-truncate"><?php echo $i.'. '.$client['name']; ?></div>
            </li>
        <?php 
                $i++;
            endforeach; 
        ?>
        </ul>
    </div>
    <?php 
            $i++;
        endforeach;
    ?>
</div>

























                
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
    // function getUserDeviceData(ua) {
    //     $.ajax({
    //         url: '/clients/analytics/ajax/chart-devices.php',
    //         method: 'GET',
    //         dataType: 'html',
    //         data: {
    //             ua: ua
    //         },
    //         success: function (data) {
    //             // console.log(data);
    //             $('#dataModalTitle').text('Clients Using '+ua);
    //             $('#dataModalBody').html(data);
    //         },
    //         error: function (e) {
    //             // var error = e.responseJSON.error;
    //             // console.log(error);
    //         }
    //     });
    // }

    document.addEventListener("DOMContentLoaded", () => {
        const triggerTabList = document.querySelectorAll('#tablist button')
triggerTabList.forEach(triggerEl => {
  const tabTrigger = new bootstrap.Tab(triggerEl)

  triggerEl.addEventListener('click', event => {
    event.preventDefault()
    tabTrigger.show()
  })
})


        const loader = '<div class="d-flex"><div class="spinner-border text-danger" role="status"><span class="visually-hidden">Loading...</span></div></div>';
        const deviceModal = new bootstrap.Modal('#deviceModal');

        const ctx = document.getElementById('chartCanvas');

        const set = {
            labels: [<?php echo $labels; ?>],
            datasets: [
                {
                    borderWidth: 1,
                    data: [<?php echo $deviceData; ?>],
                    label: "# Devices Used by Clients",
                    backgroundColor: [
                        'red',
                        'green',
                        'blue',
                        'purple',
                        'orange',
                        'yellow'
                    ]
                }
            ]
        }

        const chart = new Chart(ctx, {
            type: 'pie',
            data: set,
            options: {
                plugins: {
                    legend: {
                        onClick: function() { return; }
                    },
                },
            },
        });
        
        ctx.onclick = ( evt ) => {
            const res = chart.getElementsAtEventForMode(
                evt,
                'nearest',
                { intersect: true },
                true
            );
            if ( res.length === 0 ) {
                return;
            }

            // $('#dataModalTitle').text('Devices');
            // $('#dataModalBody').html(loader);
            // dataModal.show();
            // // console.log(res);
            // // alert('You clicked on ' + chart.data.labels[res[0].index]); //label at position index. e.g. "robert lambert"
            let ua = chart.data.labels[res[0].index];
            console.log(ua);
            // if ( !ua ) {
            //     return;
            // }
            
            // getUserDeviceData(ua);
            const triggerEl = document.querySelector('#tablist button[data-bs-target="#'+ua+'-tab-pane"]')
            console.log(triggerEl)
            bootstrap.Tab.getInstance(triggerEl).show() // Select tab by name
            deviceModal.show();
            //go to correct tab
        };
    });
</script>