Subversion Repositories SmartDukaan

Rev

Rev 36277 | Blame | Compare with Previous | Last modification | View Log | RSS feed

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
    #rbm-call-target-table th, #breakTimeDetailsContent th {
        font-size: 13px;
        text-align: center;
        padding: 0.4rem;
        vertical-align: middle;
    }

    #rbm-call-target-table td, #breakTimeDetailsContent td {
        font-size: 13px;
        text-align: center;
        padding: 0.2rem;
        vertical-align: middle;
    }

    .badge {
        display: inline-block;
        padding: 4px 8px;
        font-size: 12px;
        font-weight: 600;
        border-radius: 4px;
    }

    .agent-status-cell, .time-in-status-cell {
        min-width: 80px;
    }

    #rbm-call-target-table thead th {
        background-color: #343a40;
        color: white;
        font-weight: 600;
    }

    #rbm-call-target-table tbody tr:first-child td {
        font-weight: bold;
        background-color: #00d6b2;
    }

    .highlight-target {
        background-color: #fff3cd !important;
        font-weight: bold;
    }

    .highlight-achieved {
        background-color: #d4edda !important;
    }

    .highlight-oos {
        background-color: #f8d7da !important;
    }

    .highlight-plan-today {
        background-color: #0f57a4 !important;
        color: white !important;
    }

    .highlight-carry-forward {
        background-color: #ffc107 !important;
        color: #000 !important;
    }

    .highlight-untouched {
        background-color: #dc3545 !important;
        color: white !important;
    }

    .highlight-future-plan {
        background-color: #6c757d !important;
        color: #000 !important;
    }

    .clickable {
        cursor: pointer;
        text-decoration: underline;
        color: #007bff;
    }

    .clickable:hover {
        color: #0056b3;
    }

    .modal-body table {
        width: 100%;
    }

    .modal-body table th, .modal-body table td {
        padding: 8px;
        border: 1px solid #ddd;
    }

    #oosDetailsContent table td, #oosDetailsContent table th {
        font-size: 12px;
    }

    #calledDetailsContent table td, #calledDetailsContent table th {
        font-size: 12px;
    }
</style>

<div class="container-fluid">
    <div class="d-flex align-items-center mb-2">
        <h3 class="mb-0 mr-3">RBM Call Target Summary</h3>
        <div class="d-flex align-items-center">
            <label for="filterDate" class="mb-0 mr-2" style="font-size: 14px; white-space: nowrap;">Date:</label>
            <input type="date" id="filterDate" class="form-control form-control-sm mr-2" style="width: 150px;"
                   value="$queryDate">
            <button type="button" class="btn btn-primary btn-sm" onclick="filterByDate()">Go</button>
        </div>
    </div>
    <div class="row">
        <div class="col-md-7">
            <!-- Date-wise Called Partner Filter -->
            <div class="card mb-3" style="max-width: 500px;">
                <div class="card-body py-2">
                    <div class="d-flex align-items-center">
                        <label for="historyDate" class="mb-0 mr-2"
                               style="font-size: 14px; white-space: nowrap;">Date:</label>
                        <input type="date" id="historyDate" class="form-control form-control-sm mr-2"
                               style="width: 140px;">
                        <label for="historyRbm" class="mb-0 mr-2"
                               style="font-size: 14px; white-space: nowrap;">RBM:</label>
                        <select id="historyRbm" class="form-control form-control-sm mr-2" style="width: 150px;">
                            <option value="">Select RBM</option>
                            #foreach($model in $rbmCallTargetModels)
                                <option value="$model.getAuthId()">$model.getRbmName()</option>
                            #end
                        </select>
                        <button type="button" class="btn btn-primary btn-sm" onclick="showHistoryCalledPartners()">
                            View
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-5">
            <!-- Download All Call Data by Date -->
            <div class="card mb-3" style="max-width: 450px;">
                <div class="card-body py-2">
                    <div class="d-flex align-items-center">
                        <label for="downloadDate" class="mb-0 mr-2" style="font-size: 14px; white-space: nowrap;">Download
                            Call Data:</label>
                        <input type="date" id="downloadDate" class="form-control form-control-sm mr-2"
                               style="width: 140px;">
                        <button type="button" class="btn btn-success btn-sm" onclick="downloadCallData()">Download CSV
                        </button>
                    </div>
                </div>
            </div>

        </div>
    </div>


    <table id="rbm-call-target-table" class="table table-bordered table-striped">
        <thead>
        <tr>
            <th>RBM Name</th>
            <th style="background-color: #17a2b8; color: white;">Agent Status</th>
            <th style="background-color: #17a2b8; color: white;">Time in Status</th>
            <th style="background-color: #007bff; color: white;"><i class="fa fa-clock"></i> Login</th>
            <th style="background-color: #28a745; color: white;"><i class="fa fa-phone"></i> On Call</th>
            <th style="background-color: #dc3545; color: white;"><i class="fa fa-user-clock"></i> Idle</th>
            <th style="background-color: #fd7e14; color: white;"><i class="fa fa-coffee"></i> Break</th>
            <th>Partner Count</th>
            <th>(Ach/Tgt)</th>
            <th>Calling Target</th>
            <th>Calls / Unique</th>
            <th class="highlight-plan-today">Plan Today</th>
            <th class="highlight-carry-forward">Carry Forward</th>
            <th style="background-color: #1e6e0e; color: white;">Zero Billing</th>
            <th class="highlight-untouched">Untouched</th>
            <th class="highlight-future-plan">Future Plan</th>
            <th>Normal</th>
            <th style="background-color: #8e44ad; color: white;">Revival</th>
            <th style="background-color: #c0392b;">Out of Sequence</th>
        </tr>
        </thead>
        <tbody>
            #set($totalPartnerCount = 0)
            #set($totalTodayTarget = 0)
            #set($totalValueAchieved = 0)
            #set($totalMovedToFuture = 0)
            #set($totalPlanToday = 0)
            #set($totalCarryForward = 0)
            #set($totalZeroBilling = 0)
            #set($totalUntouched = 0)
            #set($totalFuturePlan = 0)
            #set($totalNormal = 0)
            #set($totalRevival = 0)
            #set($totalOutOfSequence = 0)
            #set($totalL2CallingList = 0)
            #set($totalL3CallingList = 0)
            #set($totalArrAchieved = 0)
            #set($totalArrTarget = 0)
            #set($totalRecordingCalls = 0)
            #set($totalUniqueRecordingCalls = 0)

            ## Total row first
            #foreach($model in $rbmCallTargetModels)
                #if(!$model.isL3Position())
                    #set($totalPartnerCount = $totalPartnerCount + $model.getPartnerCount())
                #end
                #set($totalTodayTarget = $totalTodayTarget + $model.getTodayTargetOfCall())
                #set($totalValueAchieved = $totalValueAchieved + $model.getValueTargetAchieved())
                #set($totalMovedToFuture = $totalMovedToFuture + $model.getMovedToFuture())
                #set($totalPlanToday = $totalPlanToday + $model.getPlanToday())
                #set($totalCarryForward = $totalCarryForward + $model.getCarryForward())
                #set($totalZeroBilling = $totalZeroBilling + $model.getZeroBilling())
                #set($totalUntouched = $totalUntouched + $model.getUntouched())
                #set($totalFuturePlan = $totalFuturePlan + $model.getFuturePlan())
                #set($totalNormal = $totalNormal + $model.getNormal())
                #set($totalRevival = $totalRevival + $model.getRevival())
                #set($totalOutOfSequence = $totalOutOfSequence + $model.getOutOfSequenceCount())
                #set($totalL2CallingList = $totalL2CallingList + $model.getL2CallingList())
                #set($totalL3CallingList = $totalL3CallingList + $model.getL3CallingList())
                #set($totalRecordingCalls = $totalRecordingCalls + $model.getTotalRecordingCalls())
                #set($totalUniqueRecordingCalls = $totalUniqueRecordingCalls + $model.getUniqueRecordingCalls())
                #if($arrAchievedByAuthId && $arrAchievedByAuthId.get($model.getAuthId()))
                    #set($totalArrAchieved = $totalArrAchieved + $arrAchievedByAuthId.get($model.getAuthId()))
                #end
                #if($arrTargetByAuthId && $arrTargetByAuthId.get($model.getAuthId()))
                    #set($totalArrTarget = $totalArrTarget + $arrTargetByAuthId.get($model.getAuthId()))
                #end
            #end

            #set($adjustedTotalTarget = $totalTodayTarget + $totalMovedToFuture)
            #set($adjustedTotalAchieved = $totalValueAchieved + $totalMovedToFuture)

        <tr>
            <td><strong>TOTAL</strong></td>
            <td>-</td>
            <td>-</td>
            <td>-</td>
            <td>-</td>
            <td>-</td>
            <td>-</td>
            <td><strong>$totalPartnerCount</strong></td>
            <td><strong><span class="lakh">$totalArrAchieved</span> / <span class="lakh">$totalArrTarget</span></strong>
            </td>
            <td class="highlight-target">
                #if($totalL2CallingList > 0)
                    #set($totalL1OwnTarget = $adjustedTotalTarget - $totalL2CallingList)
                    <strong>${totalL1OwnTarget} + <span style="color: #e67e22;">$totalL2CallingList</span></strong>
                #else
                    <strong>$adjustedTotalTarget</strong>
                #end
            </td>
            <td class="highlight-achieved">
                <strong><span style="color: #28a745;">$totalRecordingCalls</span>
                    / <span style="color: #007bff;">$totalUniqueRecordingCalls</span></strong>
            </td>
            <td class="highlight-plan-today"><strong>$totalPlanToday</strong></td>
            <td class="highlight-carry-forward"><strong>$totalCarryForward</strong></td>
            <td><strong>$totalZeroBilling</strong></td>
            <td class="highlight-untouched"><strong>$totalUntouched</strong></td>
            <td class="highlight-future-plan"><strong>$totalFuturePlan</strong></td>
            <td><strong>$totalNormal</strong></td>
            <td><strong>$totalRevival</strong></td>
            <td class="highlight-oos"><strong>$totalOutOfSequence</strong></td>
        </tr>

            #foreach($model in $rbmCallTargetModels)
                #set($rowTarget = $model.getTodayTargetOfCall() + $model.getMovedToFuture())
                #set($rowAchieved = $model.getValueTargetAchieved() + $model.getMovedToFuture())
                #set($agentStatus = $agentStatusByAuthId.get($model.getAuthId()))
            <tr>
                <td>$model.getRbmName()</td>
                <td class="agent-status-cell" data-authid="$model.getAuthId()">
                    #if($isToday)
                        #if($agentStatus && $agentStatus.getAgentStatus())
                            #if($agentStatus.getAgentStatus() == "On Call")
                                <span class="badge"
                                      style="background-color: #28a745; color: white;">$agentStatus.getAgentStatus()</span>
                            #elseif($agentStatus.getAgentStatus() == "Available")
                                <span class="badge"
                                      style="background-color: #dc3545; color: white;">$agentStatus.getAgentStatus()</span>
                            #elseif($agentStatus.getAgentStatus().toLowerCase().contains("break"))
                                <span class="badge"
                                      style="background-color: #fd7e14; color: white;">$agentStatus.getAgentStatus()</span>
                            #elseif($agentStatus.getAgentStatus() == "Logged Out")
                                <span class="badge"
                                      style="background-color: #6c757d; color: white;">$agentStatus.getAgentStatus()</span>
                            #elseif($agentStatus.getAgentStatus() == "Trying")
                                <span class="badge"
                                      style="background-color: #ffc107; color: black;">$agentStatus.getAgentStatus()</span>
                            #else
                                <span class="badge"
                                      style="background-color: #6c757d; color: white;">$agentStatus.getAgentStatus()</span>
                            #end
                        #else
                            <span class="badge" style="background-color: #6c757d; color: white;">-</span>
                        #end
                    #else
                        <span class="badge" style="background-color: #6c757d; color: white;">-</span>
                    #end
                </td>
                <td class="time-in-status-cell" data-authid="$model.getAuthId()">
                    #if($isToday)
                        #if($agentStatus && $agentStatus.getTimeInStatus())
                            $agentStatus.getTimeInStatus()
                        #else
                            -
                        #end
                    #else
                        -
                    #end
                </td>
                <td style="background-color: #e7f1ff;">
                    #if($loginTimeByAuthId && $loginTimeByAuthId.get($model.getAuthId()))
                        $loginTimeByAuthId.get($model.getAuthId())
                    #else
                        -
                    #end
                </td>
                <td style="background-color: #d4edda;">
                    #if($onCallTimeByAuthId && $onCallTimeByAuthId.get($model.getAuthId()))
                        $onCallTimeByAuthId.get($model.getAuthId())
                    #else
                        -
                    #end
                </td>
                <td style="background-color: #f8d7da;">
                    #if($availableTimeByAuthId && $availableTimeByAuthId.get($model.getAuthId()))
                        $availableTimeByAuthId.get($model.getAuthId())
                    #else
                        -
                    #end
                </td>
                <td style="background-color: #ffe5cc;">
                    #if($breakTimeByAuthId && $breakTimeByAuthId.get($model.getAuthId()))
                        $breakTimeByAuthId.get($model.getAuthId())
                    #else
                        -
                    #end
                </td>
                <td>$model.getPartnerCount()</td>
                <td>
                    #if($arrAchievedByAuthId && $arrAchievedByAuthId.get($model.getAuthId()))
                        <span class="lakh">$arrAchievedByAuthId.get($model.getAuthId())</span>
                    #else
                        0
                    #end
                    /
                    #if($arrTargetByAuthId && $arrTargetByAuthId.get($model.getAuthId()))
                        <span class="lakh">$arrTargetByAuthId.get($model.getAuthId())</span>
                    #else
                        0
                    #end
                </td>
                <td class="highlight-target">
                    #if($model.isL2Position() && $model.getL2CallingList() > 0)
                        #set($l1OwnTarget = $rowTarget - $model.getL2CallingList())
                        ${l1OwnTarget} + <span style="color: #e67e22; font-weight: bold;"
                                               title="L2 Escalation">$model.getL2CallingList()</span>
                    #else
                        $rowTarget
                    #end
                </td>
                <td class="highlight-achieved clickable"
                    onclick="showCalledPartnerDetails($model.getAuthId(), '$model.getRbmName()')">
                    <span style="color: #28a745; font-weight: bold;"
                          title="Total calls with recording">$model.getTotalRecordingCalls()</span>
                    / <span style="color: #007bff; font-weight: bold;"
                            title="Unique numbers with recording">$model.getUniqueRecordingCalls()</span>
                </td>
                <td class="highlight-plan-today">$model.getPlanToday()</td>
                <td class="highlight-carry-forward">$model.getCarryForward()</td>
                <td>$model.getZeroBilling()</td>
                <td class="highlight-untouched">$model.getUntouched()</td>
                <td class="highlight-future-plan">$model.getFuturePlan()</td>
                <td>$model.getNormal()</td>
                <td>$model.getRevival()</td>
                <td class="highlight-oos" style="color: red;">
                    #if($model.getOutOfSequenceCount() > 0)
                        <span class="clickable" style="color: #e80404"
                              onclick="showOutOfSequenceDetails($model.getAuthId(), '$model.getRbmName()')">$model.getOutOfSequenceCount()</span>
                    #else
                        0
                    #end
                </td>
            </tr>
            #end
        </tbody>
    </table>
</div>

<!-- Modal for Called Partner Details with Tabs -->
<div class="modal fade" id="calledModal" tabindex="-1" role="dialog" aria-labelledby="calledModalLabel"
     aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document" style="max-width: 90%;">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="calledModalLabel">Called Partners</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div id="calledDetailsContent">
                    <p>Loading...</p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Modal for Out of Sequence Details -->
<div class="modal fade" id="oosModal" tabindex="-1" role="dialog" aria-labelledby="oosModalLabel"
     aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="oosModalLabel">Out of Sequence Calls</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div id="oosDetailsContent">
                    <p>Loading...</p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    // Store globally so it persists across AJAX reloads
    window.pageQueryDate = '$queryDate';
    var pageQueryDate = window.pageQueryDate;

    function filterByDate() {
        var date = document.getElementById('filterDate').value;
        if (date) {
            var container = document.getElementById('rbm-call-target-container');
            if (container) {
                // Update global date BEFORE AJAX so click handlers use new date
                window.pageQueryDate = date;
                // AJAX reload only calling target fragment
                container.innerHTML = '<div class="text-center p-5"><i class="fa fa-spinner fa-spin fa-2x"></i><br/>Loading...</div>';
                fetch('/indent/rbm_call_target?date=' + date)
                        .then(function (response) {
                            return response.text();
                        })
                        .then(function (html) {
                            container.innerHTML = html;
                            // Re-run lakh formatting
                            var elems = container.querySelectorAll('.lakh');
                            for (var i = 0; i < elems.length; i++) {
                                var val = parseInt(elems[i].textContent.trim());
                                if (!isNaN(val)) {
                                    elems[i].textContent = (val / 100000).toFixed(1) + 'L';
                                }
                            }
                        })
                        .catch(function () {
                            container.innerHTML = '<p class="text-danger">Error loading data. Please try again.</p>';
                        });
            } else {
                // Standalone page — full reload
                window.location.href = '/indent/rbm_call_target?date=' + date;
            }
        }
    }

    // Store current authId and agentName for break time loading
    var currentModalAuthId = null;
    var currentModalDate = null;
    var currentModalAgentName = null;

    document.addEventListener('DOMContentLoaded', function () {
        var elems = document.querySelectorAll('.lakh');
        for (var i = 0; i < elems.length; i++) {
            var val = parseInt(elems[i].textContent.trim());
            if (!isNaN(val)) {
                elems[i].textContent = (val / 100000).toFixed(1) + 'L';
            }
        }
    });

    function showOutOfSequenceDetails(authId, rbmName) {
        document.getElementById('oosModalLabel').textContent = 'Out of Sequence Calls - ' + rbmName;
        document.getElementById('oosDetailsContent').innerHTML = '<p>Loading...</p>';
        $('#oosModal').modal('show');

        fetch('/indent/rbm_call_target/oos_details?authId=' + authId)
                .then(function (response) {
                    return response.json();
                })
                .then(function (data) {
                    if (data && data.length > 0) {
                        var html = '<table class="table table-bordered table-sm"><thead><tr><th>S.No</th><th>Party Name</th><th>Code</th><th>Time</th></tr></thead><tbody>';
                        for (var i = 0; i < data.length; i++) {
                            html += '<tr><td>' + (i + 1) + '</td><td>' + data[i].partyName + '</td><td>' + data[i].code + '</td><td>' + data[i].time + '</td></tr>';
                        }
                        html += '</tbody></table>';
                        document.getElementById('oosDetailsContent').innerHTML = html;
                    } else {
                        document.getElementById('oosDetailsContent').innerHTML = '<p>No out of sequence calls found.</p>';
                    }
                })
                .catch(function () {
                    document.getElementById('oosDetailsContent').innerHTML = '<p>Error loading details. Please try again.</p>';
                });
    }

    function showCalledPartnerDetails(authId, rbmName) {
        // Always use current global date (updated after AJAX reload)
        var currentDate = window.pageQueryDate;
        // Store authId and agentName for break time tab
        currentModalAuthId = authId;
        currentModalDate = currentDate;
        currentModalAgentName = rbmName;

        document.getElementById('calledModalLabel').textContent = 'Called Partners - ' + rbmName + ' (' + currentDate + ')';
        document.getElementById('calledDetailsContent').innerHTML = '<p>Loading...</p>';

        $('#calledModal').modal('show');

        var dateParam = currentDate ? '&date=' + currentDate : '';
        fetch('/indent/rbm_call_target/called_details?authId=' + authId + '&agentName=' + encodeURIComponent(rbmName) + dateParam)
                .then(function (response) {
                    return response.json();
                })
                .then(function (data) {
                    if (data && data.length > 0) {
                        var html = '<table class="table table-bordered table-sm"><thead><tr><th>S.No</th><th style="width: 200px;">Party Name</th><th>Code</th><th style="width: 350px;">Remark</th><th>Call Status</th><th>Call Duration</th><th>Call Date/Time</th><th>Recording</th></tr></thead><tbody>';
                        for (var i = 0; i < data.length; i++) {
                            var rowStyle = '';
                            var recordingHtml = '-';

                            // Break log entry — show inline with calls (sorted by time)
                            if (data[i].breakLog) {
                                var status = (data[i].breakStatus || '').toLowerCase();
                                if (status.indexOf('available') >= 0) {
                                    rowStyle = 'style="background-color: #f8d7da; color: #721c24;"'; // Light red
                                } else if (status.indexOf('trying') >= 0) {
                                    rowStyle = 'style="background-color: #fff3cd; color: #856404;"'; // Light yellow
                                } else if (status.indexOf('logged out') >= 0 || status.indexOf('logout') >= 0) {
                                    rowStyle = 'style="background-color: #e2e3e5; color: #383d41;"'; // Light grey
                                } else if (status.indexOf('break') >= 0) {
                                    rowStyle = 'style="background-color: #ffe5cc; color: #c45200;"'; // Light orange
                                } else {
                                    rowStyle = 'style="background-color: #f8f9fa; color: #333;"'; // Default light
                                }
                                var timeRange = data[i].callDateTime || '-';
                                if (data[i].breakEndTime) {
                                    var startTime = timeRange.split(' ').slice(-2).join(' '); // Get "hh:mm AM/PM"
                                    timeRange = startTime + ' to ' + data[i].breakEndTime;
                                }
                                html += '<tr ' + rowStyle + '><td>' + (i + 1) + '</td><td colspan="4"><i class="fa fa-coffee"></i> ' + (data[i].breakStatus || 'On Break') + '</td><td>' + (data[i].callDuration || '-') + '</td><td>' + timeRange + '</td><td>-</td></tr>';
                            } else {
                                if (data[i].recordingUrl) {
                                    recordingHtml = '<audio controls style="width: 150px; height: 30px;"><source src="' + data[i].recordingUrl + '" type="audio/mpeg">Your browser does not support audio.</audio>';
                                }
                                html += '<tr><td>' + (i + 1) + '</td><td>' + data[i].partyName + '</td><td>' + data[i].code + '</td><td>' + data[i].remark + '- &nbsp;' + (data[i].message || '-') + '</td><td>' + (data[i].callStatus || '-') + '</td><td>' + (data[i].callDuration || '-') + '</td><td>' + (data[i].callDateTime || '-') + '</td><td>' + recordingHtml + '</td></tr>';
                            }
                        }
                        html += '</tbody></table>';
                        document.getElementById('calledDetailsContent').innerHTML = html;
                    } else {
                        document.getElementById('calledDetailsContent').innerHTML = '<p>No called partners found.</p>';
                    }
                })
                .catch(function () {
                    document.getElementById('calledDetailsContent').innerHTML = '<p>Error loading details. Please try again.</p>';
                });
    }


    // Date-wise Called Partner History
    function showHistoryCalledPartners() {
        var selectedDate = document.getElementById('historyDate').value;
        var selectedRbm = document.getElementById('historyRbm');
        var authId = selectedRbm.value;
        var rbmName = selectedRbm.options[selectedRbm.selectedIndex].text;

        if (!selectedDate) {
            alert('Please select a date');
            return;
        }
        if (!authId) {
            alert('Please select an RBM');
            return;
        }

        // Store authId, date and agentName for break time tab
        currentModalAuthId = authId;
        currentModalDate = selectedDate;
        currentModalAgentName = rbmName;

        document.getElementById('calledModalLabel').textContent = 'Activity - ' + rbmName + ' (' + selectedDate + ')';
        document.getElementById('calledDetailsContent').innerHTML = '<p>Loading...</p>';
        document.getElementById('breakTimeDetailsContent').innerHTML = '<p>Click to load break time data.</p>';

        // Reset to Called tab
        $('#called-tab').tab('show');

        $('#calledModal').modal('show');

        fetch('/indent/rbm_call_target/called_details?authId=' + authId + '&date=' + selectedDate + '&agentName=' + encodeURIComponent(rbmName))
                .then(function (response) {
                    return response.json();
                })
                .then(function (data) {
                    if (data && data.length > 0) {
                        var html = '<table class="table table-bordered table-sm"><thead><tr><th>S.No</th><th style="width: 200px;">Party Name</th><th>Code</th><th style="width: 350px;">Remark</th><th>Call Status</th><th>Call Duration</th><th>Call Date/Time</th><th>Recording</th></tr></thead><tbody>';
                        for (var i = 0; i < data.length; i++) {
                            var rowStyle = '';
                            var recordingHtml = '-';

                            // Check if this is a break log entry
                            if (data[i].breakLog) {
                                var status = (data[i].breakStatus || '').toLowerCase();
                                if (status.indexOf('available') >= 0) {
                                    rowStyle = 'style="background-color: #f8d7da; color: #721c24;"'; // Light red
                                } else if (status.indexOf('trying') >= 0) {
                                    rowStyle = 'style="background-color: #fff3cd; color: #856404;"'; // Light yellow
                                } else if (status.indexOf('logged out') >= 0 || status.indexOf('logout') >= 0) {
                                    rowStyle = 'style="background-color: #e2e3e5; color: #383d41;"'; // Light grey
                                } else if (status.indexOf('break') >= 0) {
                                    rowStyle = 'style="background-color: #ffe5cc; color: #c45200;"'; // Light orange
                                } else {
                                    rowStyle = 'style="background-color: #f8f9fa; color: #333;"'; // Default light
                                }
                                var timeRange = data[i].callDateTime || '-';
                                if (data[i].breakEndTime) {
                                    // Extract just the time part from callDateTime and show range
                                    var startTime = timeRange.split(' ').slice(-2).join(' '); // Get "hh:mm AM/PM"
                                    timeRange = startTime + ' to ' + data[i].breakEndTime;
                                }
                                html += '<tr ' + rowStyle + '><td>' + (i + 1) + '</td><td colspan="4"><i class="fa fa-coffee"></i> ' + (data[i].breakStatus || 'On Break') + '</td><td>' + (data[i].callDuration || '-') + '</td><td>' + timeRange + '</td><td>-</td></tr>';
                            } else {
                                if (data[i].recordingUrl) {
                                    recordingHtml = '<audio controls style="width: 150px; height: 30px;"><source src="' + data[i].recordingUrl + '" type="audio/mpeg">Your browser does not support audio.</audio>';
                                }
                                html += '<tr><td>' + (i + 1) + '</td><td>' + data[i].partyName + '</td><td>' + data[i].code + '</td><td>' + data[i].remark + '- &nbsp;' + (data[i].message || '-') + '</td><td>' + (data[i].callStatus || '-') + '</td><td>' + (data[i].callDuration || '-') + '</td><td>' + (data[i].callDateTime || '-') + '</td><td>' + recordingHtml + '</td></tr>';
                            }
                        }
                        html += '</tbody></table>';
                        document.getElementById('calledDetailsContent').innerHTML = html;
                    } else {
                        document.getElementById('calledDetailsContent').innerHTML = '<p>No called partners found for selected date.</p>';
                    }
                })
                .catch(function () {
                    document.getElementById('calledDetailsContent').innerHTML = '<p>Error loading details. Please try again.</p>';
                });
    }

    // Auto-refresh agent status every 30 seconds
    function refreshAgentStatus() {
        fetch('/indent/rbm_call_target/get_agent_statuses')
                .then(function (response) {
                    return response.json();
                })
                .then(function (data) {
                    if (data && data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            var agent = data[i];
                            var statusCell = document.querySelector('.agent-status-cell[data-authid="' + agent.authId + '"]');
                            var timeCell = document.querySelector('.time-in-status-cell[data-authid="' + agent.authId + '"]');

                            if (statusCell) {
                                var statusHtml = getStatusBadge(agent.agentStatus);
                                statusCell.innerHTML = statusHtml;
                            }
                            if (timeCell) {
                                timeCell.textContent = agent.timeInStatus || '-';
                            }
                        }
                    }
                })
                .catch(function (err) {
                    console.error('Error refreshing agent status:', err);
                });
    }

    function getStatusBadge(status) {
        if (!status) return '<span class="badge" style="background-color: #6c757d; color: white;">-</span>';

        var bgColor = '#6c757d';
        var textColor = 'white';
        var lowerStatus = status.toLowerCase();

        if (status === 'On Call') {
            bgColor = '#28a745';
        } else if (status === 'Available') {
            bgColor = '#dc3545';
        } else if (lowerStatus.indexOf('break') !== -1) {
            bgColor = '#fd7e14';  // Orange for break
        } else if (status === 'Logged Out') {
            bgColor = '#6c757d';  // Grey for logged out
        } else if (status === 'Trying') {
            bgColor = '#ffc107';  // Yellow for trying
            textColor = 'black';
        }

        return '<span class="badge" style="background-color: ' + bgColor + '; color: ' + textColor + ';">' + status + '</span>';
    }

    // Refresh every 10 seconds (only for today's view)
        #if($isToday)
    setInterval(refreshAgentStatus, 10000);

    // Initial refresh after page load
    setTimeout(refreshAgentStatus, 2000);
        #end

    // Download All Call Data by Date
    function downloadCallData() {
        var selectedDate = document.getElementById('downloadDate').value;
        if (!selectedDate) {
            alert('Please select a date');
            return;
        }
        window.location.href = '/indent/rbm_call_target/download_call_data?date=' + selectedDate;
    }
</script>