
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Restaurant Shift Management</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f8f9fa;
            color: #333;
        }
        
        .wrapper {
            display: flex;
            min-height: 100vh;
        }
        
        .main-panel {
            flex: 1;
            overflow-x: hidden;
        }
        
        .container {
            padding: 20px;
        }
        
        .page-inner {
            background-color: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.05);
        }
        
        .nav-tabs .nav-link {
            color: #495057;
            font-weight: 500;
        }
        
        .nav-tabs .nav-link.active {
            font-weight: 600;
        }
        
        .card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.05);
            margin-bottom: 20px;
        }
        
        .card-header {
            border-radius: 10px 10px 0 0 !important;
            padding: 15px 20px;
        }
        
        .bg-primary {
            background-color: #4e73df !important;
        }
        
        .bg-danger {
            background-color: #e74a3b !important;
        }
        
        .btn-primary {
            background-color: #4e73df;
            border-color: #4e73df;
        }
        
        .btn-danger {
            background-color: #e74a3b;
            border-color: #e74a3b;
        }
        
        .btn-success {
            background-color: #1cc88a;
            border-color: #1cc88a;
        }
        
        .btn-warning {
            background-color: #f6c23e;
            border-color: #f6c23e;
        }
        
        .btn-info {
            background-color: #36b9cc;
            border-color: #36b9cc;
        }
        
        .badge {
            font-weight: 500;
            padding: 5px 10px;
        }
        
        .list-group-item {
            border-left: none;
            border-right: none;
        }
        
        .list-group-item:first-child {
            border-top: none;
        }
        
        .table th {
            border-top: none;
        }
        
        .shift-card {
            transition: all 0.3s;
        }
        
        .shift-card:hover {
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
        }
        
        .print-area {
            background-color: white;
            padding: 20px;
        }
        
        @media print {
            body * {
                visibility: hidden;
            }
            .print-area, .print-area * {
                visibility: visible;
            }
            .print-area {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
            }
            .no-print {
                display: none !important;
            }
        }
        
        .cash-flow-positive {
            color: #28a745;
            font-weight: bold;
        }
        
        .cash-flow-negative {
            color: #dc3545;
            font-weight: bold;
        }
        
        .btn-close-white {
            filter: invert(1);
        }
        
        .spinner-border {
            width: 1.5rem;
            height: 1.5rem;
            border-width: 0.2em;
        }
        
        .toast {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1100;
        }
    </style>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" rel="stylesheet">
</head>
<body>
  <div class="wrapper">
    <div class="main-panel">
        <div class="container">
            <div class="page-inner">
                <div class="d-flex align-items-left align-items-md-center flex-row flex-md-row pt-2 pb-4">
                    <div>
                        <h3 class="fw-bold mb-3">Restaurant Shift Management</h3>
                        <h6 class="op-7 mb-2">Manage staff shifts and cash flow</h6>
                    </div>
                </div>
                 
                <!-- Tab Navigation -->
                <ul class="nav nav-tabs" id="shiftTab" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="dashboard-tab" data-bs-toggle="tab" data-bs-target="#dashboard" type="button" role="tab" aria-controls="dashboard" aria-selected="true">
                            <i class="bi bi-speedometer2 me-1"></i> Dashboard
                        </button>
                    </li>
                    
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="new-shift-tab" data-bs-toggle="tab" data-bs-target="#new-shift" type="button" role="tab" aria-controls="new-shift" aria-selected="false">
                            <i class="bi bi-plus-circle me-1"></i> New Shift
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
    <button class="nav-link" id="active-shifts-tab" data-bs-toggle="tab" data-bs-target="#active-shifts" type="button" role="tab" aria-controls="active-shifts" aria-selected="false">
        <i class="bi bi-people-fill me-1"></i> Active Shifts
    </button>
</li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="shift-history-tab" data-bs-toggle="tab" data-bs-target="#shift-history" type="button" role="tab" aria-controls="shift-history" aria-selected="false">
                            <i class="bi bi-clock-history me-1"></i> Shift History
                        </button>
                    </li>
                    
                </ul>

                <div class="tab-content mt-3">
                    <!-- Dashboard Tab -->
                    <div class="tab-pane fade show active" id="dashboard" role="tabpanel" aria-labelledby="dashboard-tab">
                        <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                            <h2 class="h4">Shift Dashboard</h2>
                            <div class="btn-toolbar mb-2 mb-md-0">
                                <button class="btn btn-sm btn-outline-primary" id="refresh-btn">
                                    <i class="bi bi-arrow-clockwise"></i> Refresh
                                </button>
                            </div>
                        </div>

                        <!-- Current Shift Info -->
                        <div class="row mb-4" id="current-shift-container">
                            <div class="col-12">
                                <div class="card">
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <h4 class="card-title">Current Shift Status</h4>
                                                <div class="d-flex align-items-center mb-3">
                                                    <div class="me-3">
                                                        <div class="avatar avatar-lg">
                                                            <span class="avatar-title rounded-circle bg-primary text-white">
                                                                <i class="bi bi-person-fill"></i>
                                                            </span>
                                                        </div>
                                                    </div>
                                                    <div>
                                                        <h5 id="current-employee-name">Loading...</h5>
                                                        <p class="text-muted mb-0" id="current-shift-status">Status: Loading</p>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="row">
                                                    <div class="col-6">
                                                        <div class="card bg-light mb-3">
                                                            <div class="card-body text-center">
                                                                <h6 class="card-subtitle mb-2 text-muted">Start Time</h6>
                                                                <p class="card-text" id="shift-start-time">--:--</p>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="col-6">
                                                        <div class="card bg-light mb-3">
                                                            <div class="card-body text-center">
                                                                <h6 class="card-subtitle mb-2 text-muted">Duration</h6>
                                                                <p class="card-text" id="shift-duration">0h 0m</p>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Financial Summary -->
                        <div class="row mb-4">
                            <div class="col-md-4">
                                <div class="card">
    <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Cash Summary</h5>
        <button id="refresh-cash-summary" class="btn btn-sm btn-light">
            <i class="bi bi-arrow-clockwise"></i> Refresh
        </button>
    </div>
    <div class="card-body">
       
        <div class="d-flex justify-content-between mb-2">
            <span>Cash Payments:</span>
            <strong id="cash-payments">$0.00</strong>
        </div>
        <div class="d-flex justify-content-between mb-2">
            <span>Expenses:</span>
            <strong id="cash-expenses">$0.00</strong>
        </div>
        <hr>
       
        <div class="d-flex justify-content-between mb-2">
            <span>Difference:</span>
            <strong id="cash-difference">$0.00</strong>
        </div>
        <div class="text-end">
            <small class="text-muted" id="cash-summary-time"></small>
        </div>
    </div>
</div>
                            </div>
                            <div class="col-md-4">
                                <div class="card">
                                    <div class="card-header bg-success text-white">
                                        <h5 class="mb-0">Sales Summary</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between mb-3">
                                            <span>Total Sales:</span>
                                            <strong id="total-sales">$0.00</strong>
                                        </div>
                                        <div class="d-flex justify-content-between mb-3">
                                            <span>Total Payments:</span>
                                            <strong id="total-payments">$0.00</strong>
                                        </div>
                                        <div class="d-flex justify-content-between">
                                            <span>Outstanding Debt:</span>
                                            <strong id="total-debt">$0.00</strong>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="card">
                                    <div class="card-header bg-info text-white">
                                        <h5 class="mb-0">Shift Actions</h5>
                                    </div>
                                    <div class="card-body text-center">
                                        <button class="btn btn-success me-2 mb-2" id="start-shift-btn">
                                            <i class="bi bi-play-circle"></i> Start Shift
                                        </button>
                                        <button class="btn btn-danger me-2 mb-2" id="close-shift-btn" disabled>
                                            <i class="bi bi-stop-circle"></i> Close Shift
                                        </button>
                                        <!-- Button to trigger report generation -->
<button id="btnGenerateReport" class="btn btn-primary">
    <i class="fas fa-file-alt"></i> Generate Active Shifts Report
</button>

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

                        <!-- Recent Transactions and Payments -->
                        <div class="row">
                            <div class="col-md-6">
                                <div class="card mb-4">
                                    <div class="card-header bg-primary text-white">
                                        <h5 class="mb-0">Recent Transactions</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="table-responsive">
                                            <table class="table table-hover" id="recent-transactions-table">
                                                <thead>
                                                    <tr>
                                                        <th>ID</th>
                                                        <th>Customer</th>
                                                        <th>Amount</th>
                                                        <th>Status</th>
                                                    </tr>
                                                </thead>
                                                <tbody id="recent-transactions-container">
                                                    <tr>
                                                        <td colspan="4" class="text-center">No recent transactions</td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="card mb-4">
                                    <div class="card-header bg-primary text-white">
                                        <h5 class="mb-0">Recent Payments</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="table-responsive">
                                            <table class="table table-hover" id="recent-payments-table">
                                                <thead>
                                                    <tr>
                                                        <th>Method</th>
                                                        <th>Amount</th>
                                                        <th>Transaction</th>
                                                    </tr>
                                                </thead>
                                                <tbody id="recent-payments-container">
                                                    <tr>
                                                        <td colspan="3" class="text-center">No recent payments</td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- New Shift Tab -->
                    <div class="tab-pane fade" id="new-shift" role="tabpanel" aria-labelledby="new-shift-tab">
                        <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                            <h2 class="h4">Start New Shift</h2>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header bg-primary text-white">
                                        <h5 class="mb-0">Shift Information</h5>
                                    </div>
                                    <div class="card-body">
                                        <form id="start-shift-form">
                                            <div class="mb-3">
                                                <label for="employee-id" class="form-label">Employee *</label>
                                                <select class="form-select" id="employee-id" required>
                                                    <option value="">Select Employee</option>
                                                    <!-- Will be populated by JavaScript -->
                                                </select>
                                            </div>
                                            <div class="mb-3">
                                                <label for="opening-float" class="form-label">Opening Cash Amount *</label>
                                                <div class="input-group">
                                                    <span class="input-group-text">$</span>
                                                    <input type="number" class="form-control" id="opening-float" step="0.01" min="0" required>
                                                </div>
                                            </div>
                                            <div class="mb-3">
                                                <label for="shift-notes" class="form-label">Notes</label>
                                                <textarea class="form-control" id="shift-notes" rows="2"></textarea>
                                            </div>
                                            <button type="submit" class="btn btn-primary">
                                                <i class="bi bi-play-circle me-1"></i> Start Shift
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header bg-primary text-white">
                                        <h5 class="mb-0">Last Shift Summary</h5>
                                    </div>
                                    <div class="card-body">
                                        <div id="last-shift-summary">
                                            <div class="text-center">
                                                <div class="spinner-border text-primary" role="status">
                                                    <span class="visually-hidden">Loading...</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Shift History Tab -->
                    <div class="tab-pane fade" id="shift-history" role="tabpanel" aria-labelledby="shift-history-tab">
                        <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                            <h2 class="h4">Shift History</h2>
                            <div class="btn-toolbar mb-2 mb-md-0">
                                <div class="btn-group me-2">
                                    <input type="date" class="form-control" id="history-date-filter">
                                    <button class="btn btn-outline-secondary" id="filter-history-btn">
                                        <i class="bi bi-funnel"></i> Filter
                                    </button>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-12">
                                <div class="card">
                                    <div class="card-header bg-primary text-white">
                                        <h5 class="mb-0">Past Shifts</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="table-responsive">
                                            <table class="table table-hover" id="shift-history-table">
                                                <thead>
                                                    <tr>
                                                        <th>Shift ID</th>
                                                        <th>Employee</th>
                                                        <th>Start Time</th>
                                                        <th>End Time</th>
                                                        <th>Opening Cash</th>
                                                        <th>Closing Cash</th>
                                                        <th>Variance</th>
                                                        <th>Status</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody id="shift-history-container">
                                                    <tr>
                                                        <td colspan="9" class="text-center">
                                                            <div class="spinner-border text-primary" role="status">
                                                                <span class="visually-hidden">Loading...</span>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                        <nav aria-label="Shift history pagination">
                                            <ul class="pagination justify-content-center" id="shift-history-pagination">
                                                <!-- Pagination will be added here by JavaScript -->
                                            </ul>
                                        </nav>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Add this tab pane to your tab content -->
                    <div class="tab-pane fade" id="active-shifts" role="tabpanel" aria-labelledby="active-shifts-tab">
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <h2 class="h4">Currently Active Shifts</h2>
        <div class="btn-toolbar mb-2 mb-md-0">
            <button class="btn btn-sm btn-outline-primary" id="refresh-active-shifts">
                <i class="bi bi-arrow-clockwise"></i> Refresh
            </button>
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0">Active Shifts Overview</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Employee</th>
                                    <th>Start Time</th>
                                    <th>Duration</th>
                                    <th>Total Sales</th>
                                    <th>Total Payments</th>
                                    <th>Outstanding Debt</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="active-shifts-container">
                                <tr>
                                    <td colspan="7" class="text-center">
                                        <div class="spinner-border text-primary" role="status">
                                            <span class="visually-hidden">Loading...</span>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
                </div>
            </div>
        </div>
    </div>

   <!-- Close Shift Modal -->
    <div class="modal fade" id="closeShiftModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title">Close Shift</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="close-shift-form">
                        <input type="hidden" id="close-shift-id">
                        <input type="hidden" id="close-opening-float">
                        
                        <div class="mb-3">
                            <label for="closing-float" class="form-label">Closing Cash Amount *</label>
                            <div class="input-group">
                                <span class="input-group-text">$</span>
                                <input type="number" class="form-control" id="closing-float" step="0.01" min="0" required>
                            </div>
                            <small class="text-muted">Expected: <span id="expected-closing-cash">$0.00</span></small>
                        </div>
                        
                        <div class="mb-3">
                            <label for="close-notes" class="form-label">Closing Notes</label>
                            <textarea class="form-control" id="close-notes" rows="3"></textarea>
                        </div>
                        
                        <div class="alert alert-info">
                            <i class="bi bi-info-circle"></i> Please verify all cash movements and transactions before closing the shift.
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-danger" id="confirm-close-btn">Close Shift</button>
                </div>
            </div>
        </div>
    </div>
    
    <div class="modal fade" id="shiftReportModal" tabindex="-1" aria-labelledby="shiftReportModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="shiftReportModalLabel">Shift Report</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="shift-report-content"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Loading spinner (hidden by default) -->
<div id="loading-spinner" style="display: none;">
    <i class="fas fa-spinner fa-spin"></i> Generating report...
</div>

<!-- Modal for displaying report -->
<div class="modal fade" id="reportModal" tabindex="-1" role="dialog" aria-labelledby="reportModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="reportModalLabel">Report</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <!-- Report content will be inserted here -->
            </div>
        </div>
    </div>
</div>

</div>

<style>
    .print-area {
        background-color: white;
        color: black;
    }
    
    @media print {
        body * {
            visibility: hidden;
        }
        .print-area, .print-area * {
            visibility: visible;
        }
        .print-area {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
        }
        .no-print {
            display: none !important;
        }
    }
</style>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
   <script>
$(document).ready(function() {
    // Global variables
    let currentShift = null;
    let currentUser = <?php echo json_encode($_SESSION['user'] ?? null); ?>;
    let employees = [];
    let shiftTransactions = [];
    
    // Initialize the page
    initPage();
    
    function initPage() {
        loadEmployees();
        checkCurrentShift();
        loadLastShift();
        loadActiveShifts();
        loadShiftHistory();
        
        // Set up event listeners
        $('#start-shift-form').on('submit', function(e) {
            e.preventDefault();
            startShift();
        });
        
        $('#close-shift-btn').click(function() {
            if (currentShift) {
                prepareCloseShiftModal();
            }
        });
        
        
      
        $('#view-report-btn').click(function() {
            if (currentShift) {
                generateShiftReport(currentShift.shift_id);
            }
        });
        
        $('#refresh-btn').click(function() {
            refreshData();
        });
        
        $('#confirm-close-btn').click(function() {
            closeShift();
        });
        
        $('#filter-history-btn').click(function() {
            loadShiftHistory();
        });
        
        $('#btnGenerateReport').click(function() {
             fetchAndDisplayActiveShiftsReport();
        });
       
        
        $('#refresh-active-shifts').click(function() {
            loadActiveShifts();
        });
    }
    
    function loadEmployees() {
        $.ajax({
            url: './database/shift_actions.kts.php',
            type: 'GET',
            data: { action: 'get_employees' },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    employees = response.data;
                    populateEmployeeDropdowns();
                } else {
                    toastr.error(response.message);
                }
            },
            error: function(xhr, status, error) {
                toastr.error('Failed to load employees: ' + error);
            }
        });
    }
    
    function startShift() {
            const employeeId = $('#employee-id').val();
            const openingFloat = parseFloat($('#opening-float').val());
            const notes = $('#shift-notes').val();
            
            if (!employeeId || isNaN(openingFloat)) {
                toastr.error('Please fill all required fields');
                return;
            }
            
            $.ajax({
                url: './database/shift_actions.kts.php',
                type: 'POST',
                data: { 
                    action: 'start_shift',
                    employee_id: employeeId,
                    starting_cash: openingFloat,
                    notes: notes
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        toastr.success('Shift started successfully');
                        currentShift = response.data;
                        refreshData();
                        $('#dashboard-tab').tab('show');
                    } else {
                        toastr.error(response.message);
                    }
                },
                error: function(xhr, status, error) {
                    toastr.error('Failed to start shift: ' + error);
                }
            });
        }
     
    function populateEmployeeDropdowns() {
        const employeeDropdown = $('#employee-id');
        employeeDropdown.empty().append('<option value="">Select Employee</option>');
        
        employees.forEach(employee => {
            employeeDropdown.append(`<option value="${employee.employee_id}">${employee.name}</option>`);
        });
    }
    
    function loadActiveShifts() {
        $.ajax({
            url: './database/shift_actions.kts.php',
            type: 'GET',
            data: { action: 'get_active_shifts' },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    const container = $('#active-shifts-container');
                    container.empty();
                    
                    if (response.data && response.data.length > 0) {
                        let html = '<table class="table table-striped"><thead><tr>' +
                            '<th>Employee</th><th>Start Time</th><th>Duration</th>' +
                            '<th>Sales</th><th>Payments</th><th>Debt</th><th>Actions</th></tr></thead><tbody>';
                        
                        response.data.forEach(shift => {
                            const duration = calculateShiftDuration(shift.start_time);
                            const totalSales = parseFloat(shift.total_orders || 0);
                            const totalPayments = parseFloat(shift.total_payments || 0);
                            const totalDebt = parseFloat(shift.total_debt || 0);
                            
                            html += `
                                <tr>
                                    <td>${shift.employee_name || 'Unknown'}</td>
                                    <td>${formatDateTime(shift.start_time)}</td>
                                    <td>${duration}</td>
                                    <td>$${totalSales.toFixed(2)}</td>
                                    <td>$${totalPayments.toFixed(2)}</td>
                                    <td>$${totalDebt.toFixed(2)}</td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-primary view-shift-btn" data-id="${shift.shift_id}">
                                            <i class="bi bi-eye"></i> View
                                        </button>
                                    </td>
                                </tr>
                            `;
                        });
                        
                        html += '</tbody></table>';
                        container.html(html);
                        
                        // Add click handlers for view buttons
                        $('.view-shift-btn').click(function() {
                            const shiftId = $(this).data('id');
                            generateShiftReport(shiftId);
                        });
                    } else {
                        container.html('<div class="alert alert-info">No active shifts found</div>');
                    }
                } else {
                    toastr.error(response.message);
                }
            },
            error: function(xhr, status, error) {
                toastr.error('Failed to load active shifts: ' + error);
                $('#active-shifts-container').html('<div class="alert alert-danger">Failed to load active shifts</div>');
            }
        });
    }
    
    function checkCurrentShift() {
        $.ajax({
            url: './database/shift_actions.kts.php',
            type: 'GET',
            data: { action: 'get_current_shift' },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    // Ensure numeric values are properly parsed
                    if (response.data) {
                        currentShift = {
                            ...response.data,
                            starting_cash: parseFloat(response.data.starting_cash || 0),
                            total_orders: parseFloat(response.data.total_orders || 0),
                            total_payments: parseFloat(response.data.total_payments || 0),
                            total_debt: parseFloat(response.data.total_debt || 0)
                        };
                    }
                    updateShiftUI();
                    
                    if (currentShift) {
                        loadShiftTransactions(currentShift.shift_id);
                    }
                } else {
                    toastr.error(response.message);
                }
            },
            error: function(xhr, status, error) {
                toastr.error('Failed to check current shift: ' + error);
            }
        });
    }
    
    function updateShiftUI() {
        const startBtn = $('#start-shift-btn');
        const closeBtn = $('#close-shift-btn');
        const reportBtn = $('#view-report-btn');
        
        if (currentShift) {
            startBtn.prop('disabled', true);
            closeBtn.prop('disabled', false);
            reportBtn.prop('disabled', false);
            
            const employee = employees.find(e => e.employee_id == currentShift.employee_id) || {};
            const totalSales = parseFloat(currentShift.total_orders || 0);
            const totalPayments = parseFloat(currentShift.total_payments || 0);
            const totalDebt = parseFloat(currentShift.total_debt || 0);
            
            const shiftHtml = `
                <div class="card bg-light">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <h4>Current Shift</h4>
                                <p><strong>Employee:</strong> ${employee.name || 'Unknown'}</p>
                                <p><strong>Started:</strong> ${formatDateTime(currentShift.start_time)}</p>
                                <p><strong>Opening Cash:</strong> $${parseFloat(currentShift.starting_cash || 0).toFixed(2)}</p>
                                <p><strong>Total Sales:</strong> $${totalSales.toFixed(2)}</p>
                                <p><strong>Total Payments:</strong> $${totalPayments.toFixed(2)}</p>
                                <p><strong>Outstanding Debt:</strong> $${totalDebt.toFixed(2)}</p>
                            </div>
                            <div class="col-md-6 text-end">
                                <h4>Shift Status: <span class="badge bg-success">Active</span></h4>
                                <p><strong>Duration:</strong> ${calculateShiftDuration(currentShift.start_time)}</p>
                                <button class="btn btn-danger mt-2" id="force-close-btn">
                                    <i class="bi bi-stop-circle"></i> Close Shift
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            $('#current-shift-container').html(shiftHtml);
            $('#force-close-btn').click(prepareCloseShiftModal);
        } else {
            startBtn.prop('disabled', false);
            closeBtn.prop('disabled', true);
            reportBtn.prop('disabled', true);
            
            $('#current-shift-container').html(`
                <div class="card bg-light">
                    <div class="card-body text-center">
                        <h4>No Active Shift</h4>
                        <p>There is currently no active shift. Start a new shift to begin recording transactions.</p>
                        <button class="btn btn-primary" id="start-shift-btn-top">
                            <i class="bi bi-play-circle"></i> Start New Shift
                        </button>
                    </div>
                </div>
            `);
            
            $('#start-shift-btn-top').click(function() {
                $('#new-shift-tab').tab('show');
            });
        }
    }
    
    function prepareCloseShiftModal() {
        if (!currentShift) return;
        
        $('#close-shift-id').val(currentShift.shift_id);
        $('#close-opening-float').val(currentShift.starting_cash.toFixed(2));
        $('#closing-float').val('');
        $('#close-notes').val('');
        
        // Safely calculate expected closing amount
        const startingCash = parseFloat(currentShift.starting_cash) || 0;
        const totalPayments = parseFloat(currentShift.total_payments) || 0;
        const expectedClosing = startingCash + totalPayments;
        
        // Set the calculated amount as a placeholder
        $('#closing-float').attr('placeholder', expectedClosing.toFixed(2));
        
        const modal = new bootstrap.Modal(document.getElementById('closeShiftModal'));
        modal.show();
    }
    
    function closeShift() {
        const shiftId = $('#close-shift-id').val();
        const closingFloat = parseFloat($('#closing-float').val());
        const notes = $('#close-notes').val();
        
        if (isNaN(closingFloat)) {
            toastr.error('Please enter a valid closing amount');
            return;
        }
        
        $.ajax({
            url: './database/shift_actions.kts.php',
            type: 'POST',
            data: { 
                action: 'close_shift',
                shift_id: shiftId,
                ending_cash: closingFloat,
                notes: notes
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    toastr.success('Shift closed successfully');
                    currentShift = null;
                    
                    // Close modal
                    bootstrap.Modal.getInstance(document.getElementById('closeShiftModal')).hide();
                    
                    refreshData();
                } else {
                    toastr.error(response.message);
                }
            },
            error: function(xhr, status, error) {
                toastr.error('Failed to close shift: ' + error);
            }
        });
    }
    
    
    // Generate shift report
function generateShiftReport(shiftId) {
    $.ajax({
        url: './database/shift_actions.kts.php',
        type: 'GET',
        data: { 
            action: 'get_shift_report',
            shift_id: shiftId
        },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                const shift = response.data.shift;
                const transactions = response.data.transactions || [];
                const summary = response.data.summary;
                
                // Generate report HTML with thermal printer friendly styling
                let html = `
                    <div class="shift-report thermal-print">
                        <style>
                            .thermal-print {
                                font-family: Arial, sans-serif;
                                font-size: 12px;
                                width: 100%;
                                max-width: 80mm;
                                margin: 0 auto;
                            }
                            .thermal-print .text-center {
                                text-align: center;
                            }
                            .thermal-print table {
                                width: 100%;
                                border-collapse: collapse;
                                margin-bottom: 10px;
                            }
                            .thermal-print th, .thermal-print td {
                                padding: 4px;
                                border: 1px solid #ddd;
                            }
                            .thermal-print .bold {
                                font-weight: bold;
                            }
                            .thermal-print .underline {
                                border-bottom: 1px dashed #000;
                                margin: 5px 0;
                            }
                            .thermal-print .divider {
                                border-top: 1px dashed #000;
                                margin: 10px 0;
                            }
                        </style>
                        
                        <div class="text-center">
                            <h3>SHIFT REPORT</h3>
                            <p>Shift #${shift.shift_id}</p>
                            <p>Employee: ${shift.employee_name}</p>
                            <p>${formatDateTime(new Date())}</p>
                            <div class="divider"></div>
                        </div>
                        
                        <div class="shift-details">
                            <table>
                                <tr>
                                    <th colspan="2">SHIFT DETAILS</th>
                                </tr>
                                <tr>
                                    <td>Start Time:</td>
                                    <td>${formatDateTime(shift.start_time)}</td>
                                </tr>
                                <tr>
                                    <td>End Time:</td>
                                    <td>${shift.end_time ? formatDateTime(shift.end_time) : 'Not closed'}</td>
                                </tr>
                                <tr>
                                    <td>Status:</td>
                                    <td>${shift.status === 'active' ? 'Active' : 'Closed'}</td>
                                </tr>
                                <tr>
                                    <td>Opening Cash:</td>
                                    <td>${parseFloat(shift.starting_cash).toFixed(2)}</td>
                                </tr>
                                <tr>
                                    <td>Closing Cash:</td>
                                    <td>${shift.ending_cash ? parseFloat(shift.ending_cash).toFixed(2) : 'N/A'}</td>
                                </tr>
                                <tr>
                                    <td>Total Orders:</td>
                                    <td>${parseFloat(shift.total_orders).toFixed(2)}</td>
                                </tr>
                                <tr>
                                    <td>Total Payments:</td>
                                    <td>${parseFloat(shift.total_payments).toFixed(2)}</td>
                                </tr>
                                <tr>
                                    <td>Total Debt:</td>
                                    <td>${parseFloat(shift.total_debt).toFixed(2)}</td>
                                </tr>
                            </table>
                            <div class="divider"></div>
                        </div>
                        
                        <div class="sales-summary">
                            <table>
                                <tr>
                                    <th colspan="4">SALES SUMMARY</th>
                                </tr>
                                <tr>
                                    <th>Product</th>
                                    <th>Qty</th>
                                    <th>Price</th>
                                    <th>Subtotal</th>
                                </tr>
                `;
                
                // Add sales items
                let allSalesItems = [];
                transactions.forEach(trans => {
                    if (trans.items && trans.items.length > 0) {
                        allSalesItems = allSalesItems.concat(trans.items);
                    }
                });
                
                // Group by product name and sum quantities/subtotals
                const productSummary = {};
                allSalesItems.forEach(item => {
                    if (!productSummary[item.product_name]) {
                        productSummary[item.product_name] = {
                            quantity: 0,
                            selling_price: parseFloat(item.selling_price),
                            subtotal: 0
                        };
                    }
                    productSummary[item.product_name].quantity += parseFloat(item.quantity);
                    productSummary[item.product_name].subtotal += parseFloat(item.subtotal);
                });
                
                // Add product rows
                Object.keys(productSummary).forEach(productName => {
                    const item = productSummary[productName];
                    html += `
                        <tr>
                            <td>${productName}</td>
                            <td>${item.quantity.toFixed(2)}</td>
                            <td>${item.selling_price.toFixed(2)}</td>
                            <td>${item.subtotal.toFixed(2)}</td>
                        </tr>
                    `;
                });
                
                // Add sales totals
                html += `
                                <tr class="bold">
                                    <td colspan="3">TOTAL SALES</td>
                                    <td>${parseFloat(summary.total_sales).toFixed(2)}</td>
                                </tr>
                            </table>
                            <div class="divider"></div>
                        </div>
                        
                        <div class="payments-summary">
                            <table>
                                <tr>
                                    <th colspan="2">PAYMENTS SUMMARY</th>
                                </tr>
                                <tr>
                                    <th>Method</th>
                                    <th>Amount</th>
                                </tr>
                `;
                
                // Add payment methods
                if (summary.payment_method_totals) {
                    Object.keys(summary.payment_method_totals).forEach(method => {
                        html += `
                            <tr>
                                <td>${method}</td>
                                <td>${parseFloat(summary.payment_method_totals[method]).toFixed(2)}</td>
                            </tr>
                        `;
                    });
                }
                
                // Add payment totals
                html += `
                                <tr class="bold">
                                    <td>TOTAL RECEIVED</td>
                                    <td>${parseFloat(summary.total_received).toFixed(2)}</td>
                                </tr>
                            </table>
                            <div class="divider"></div>
                        </div>
                        
                        <div class="financial-summary">
                            <table>
                                <tr>
                                    <th colspan="2">FINANCIAL SUMMARY</th>
                                </tr>
                                <tr>
                                    <td>Total Sales:</td>
                                    <td>${parseFloat(summary.total_sales).toFixed(2)}</td>
                                </tr>
                                <tr>
                                    <td>Total Received:</td>
                                    <td>${parseFloat(summary.total_received).toFixed(2)}</td>
                                </tr>
                                <tr class="bold">
                                    <td>Outstanding Debt:</td>
                                    <td>${parseFloat(summary.total_debt).toFixed(2)}</td>
                                </tr>
                            </table>
                        </div>
                        
                        <div class="text-center" style="margin-top: 20px;">
                            <p>--- END OF REPORT ---</p>
                        </div>
                    </div>
                    
                    <div class="text-center mt-3">
                        <button class="btn btn-primary" onclick="window.printShiftReport()">Print Report</button>
                    </div>
                `;
                
                $('#shift-report-content').html(html);
                
                // Attach print function to window
                window.printShiftReport = function() {
                    const printContent = $('.thermal-print').clone();
                    const printWindow = window.open('', '_blank', 'width=340,height=600');
                    
                    const printHtml = `
                        <html>
                            <head>
                                <title>Shift Report</title>
                                <style>
                                    body {
                                        font-family: Arial, sans-serif;
                                        font-size: 12px;
                                        width: 80mm;
                                        margin: 0;
                                        padding: 0;
                                    }
                                    table {
                                        width: 100%;
                                        border-collapse: collapse;
                                    }
                                    th, td {
                                        padding: 4px;
                                        border: 1px solid #ddd;
                                    }
                                    .text-center {
                                        text-align: center;
                                    }
                                    .bold {
                                        font-weight: bold;
                                    }
                                    .divider {
                                        border-top: 1px dashed #000;
                                        margin: 10px 0;
                                    }
                                </style>
                            </head>
                            <body>
                                ${printContent.html()}
                            </body>
                        </html>
                    `;
                    
                    printWindow.document.open();
                    printWindow.document.write(printHtml);
                    printWindow.document.close();
                    
                    // Give it a moment to load before printing
                    setTimeout(() => {
                        printWindow.print();
                        printWindow.close();
                    }, 500);
                };
                
                const modal = new bootstrap.Modal(document.getElementById('shiftReportModal'));
                modal.show();
            } else {
                toastr.error(response.message);
            }
        },
        error: function(xhr, status, error) {
            toastr.error('Failed to generate report: ' + error);
        }
    });
}

// Format date time function
function formatDateTime(date) {
    if (!date) return '';
    if (typeof date === 'string') {
        date = new Date(date);
    }
    const options = {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    };
    return date.toLocaleString('en-US', options);
}

    // Load last shift
    function loadLastShift() {
        $.ajax({
            url: './database/shift_actions.kts.php',
            type: 'GET',
            data: { action: 'get_last_shift' },
            dataType: 'json',
            success: function(response) {
                if (response.success && response.data) {
                    const shift = response.data;
                    const employee = employees.find(e => e.employee_id == shift.employee_id);
                    const employeeName = employee ? employee.name : 'Unknown';
                    
                    let summaryHtml = `
                        <h5>Last Shift</h5>
                        <p><strong>Employee:</strong> ${employeeName}</p>
                        <p><strong>Date:</strong> ${formatDate(shift.end_time)}</p>
                        <p><strong>Duration:</strong> ${calculateShiftDuration(shift.start_time, shift.end_time)}</p>
                        <p><strong>Sales:</strong> $${shift.total_sales.toFixed(2)}</p>
                        <p><strong>Payments:</strong> $${shift.total_payments.toFixed(2)}</p>
                        <p><strong>Debt:</strong> $${shift.total_debt.toFixed(2)}</p>
                    `;
                    
                    $('#last-shift-summary').html(summaryHtml);
                } else {
                    $('#last-shift-summary').html('<p class="text-muted">No previous shift data available</p>');
                }
            },
            error: function(xhr, status, error) {
                $('#last-shift-summary').html('<p class="text-danger">Failed to load last shift data</p>');
            }
        });
    }
    
    // Load all active shifts
    function loadAllActiveShifts() {
        $.ajax({
            url: './database/shift_actions.kts.php',
            type: 'GET',
            data: { action: 'get_all_shifts' },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    const container = $('#active-shifts-container');
                    
                    if (response.data.length > 0) {
                        let html = '<div class="list-group">';
                        
                        response.data.forEach(shift => {
                            const employee = employees.find(e => e.employee_id == shift.employee_id);
                            const employeeName = employee ? employee.name : 'Unknown';
                            
                            html += `
                                <div class="list-group-item">
                                    <div class="d-flex w-100 justify-content-between">
                                        <h5 class="mb-1">${employeeName}</h5>
                                        <small>${calculateShiftDuration(shift.start_time)}</small>
                                    </div>
                                    <div class="d-flex justify-content-between">
                                        <p class="mb-1">Started: ${formatDateTime(shift.start_time)}</p>
                                        <p class="mb-1">Sales: $${shift.total_sales.toFixed(2)}</p>
                                    </div>
                                </div>
                            `;
                        });
                        
                        html += '</div>';
                        container.html(html);
                    } else {
                        container.html('<p class="text-muted">No active shifts found</p>');
                    }
                } else {
                    toastr.error(response.message);
                }
            },
            error: function(xhr, status, error) {
                toastr.error('Failed to load active shifts: ' + error);
            }
        });
    }
    
    // Load shift history
    function loadShiftHistory(page = 1) {
        const dateFilter = $('#history-date-filter').val();
        
        $.ajax({
            url: './database/shift_actions.kts.php',
            type: 'GET',
            data: { 
                action: 'get_shift_history',
                date: dateFilter,
                page: page
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    const historyContainer = $('#shift-history-container');
                    const paginationContainer = $('#shift-history-pagination');
                    
                    if (response.data.shifts.length > 0) {
                        let html = '';
                        
                        response.data.shifts.forEach(shift => {
                            const employee = employees.find(e => e.employee_id == shift.employee_id);
                            const employeeName = employee ? employee.name : 'Unknown';
                            
                            const endTime = shift.end_time ? formatDateTime(shift.end_time) : 'Not closed';
                            const closingCash = shift.ending_cash ? `$${shift.ending_cash.toFixed(2)}` : 'N/A';
                            
                            html += `
                                <tr>
                                    <td>${shift.shift_id}</td>
                                    <td>${employeeName}</td>
                                    <td>${formatDateTime(shift.start_time)}</td>
                                    <td>${endTime}</td>
                                    <td>$${shift.starting_cash.toFixed(2)}</td>
                                    <td>${closingCash}</td>
                                    <td>$${shift.total_sales.toFixed(2)}</td>
                                    <td>$${shift.total_payments.toFixed(2)}</td>
                                    <td>
                                        ${shift.status === 'active' ? 
                                            '<span class="badge bg-success">Active</span>' : 
                                            '<span class="badge bg-secondary">Closed</span>'}
                                    </td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-primary view-shift-btn" data-id="${shift.shift_id}">
                                            <i class="bi bi-eye"></i> View
                                        </button>
                                    </td>
                                </tr>
                            `;
                        });
                        
                        historyContainer.html(html);
                        
                        // Set up view buttons
                        $('.view-shift-btn').click(function() {
                            const shiftId = $(this).data('id');
                            generateShiftReport(shiftId);
                        });
                        
                        // Set up pagination
                        paginationContainer.empty();
                        
                        if (response.data.total_pages > 1) {
                            for (let i = 1; i <= response.data.total_pages; i++) {
                                const activeClass = i === page ? 'active' : '';
                                paginationContainer.append(`
                                    <li class="page-item ${activeClass}">
                                        <a class="page-link" href="#" data-page="${i}">${i}</a>
                                    </li>
                                `);
                            }
                            
                            // Set up pagination click handlers
                            $('.page-link').click(function(e) {
                                e.preventDefault();
                                const page = $(this).data('page');
                                loadShiftHistory(page);
                            });
                        }
                    } else {
                        historyContainer.html('<tr><td colspan="10" class="text-center">No shift history found</td></tr>');
                        paginationContainer.empty();
                    }
                } else {
                    toastr.error(response.message);
                }
            },
            error: function(xhr, status, error) {
                toastr.error('Failed to load shift history: ' + error);
            }
        });
    }
    
    // Refresh all data
    function refreshData() {
        checkCurrentShift();
        if (currentShift) {
            loadShiftTransactions(currentShift.shift_id);
        }
        loadLastShift();
        loadAllActiveShifts();
        loadShiftHistory();
    }
    
    // Helper function to format date/time
    function formatDateTime(datetimeString) {
        if (!datetimeString) return 'N/A';
        
        const date = new Date(datetimeString);
        return date.toLocaleString();
    }
    
    // Helper function to format date only
    function formatDate(dateString) {
        if (!dateString) return 'N/A';
        
        const date = new Date(dateString);
        return date.toLocaleDateString();
    }
    
    // Helper function to calculate shift duration
    function calculateShiftDuration(startTime, endTime = null) {
        const start = new Date(startTime);
        const end = endTime ? new Date(endTime) : new Date();
        
        const diffMs = end - start;
        const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
        const diffMinutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
        
        return `${diffHours}h ${diffMinutes}m`;
    }
    
    
    function fetchActiveShiftsSummary() {
    fetch('./database/shift_actions.kts.php?action=get_active_shifts_summary')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayActiveShiftsSummary(data.data);
            } else {
                console.error('Error:', data.message);
                alert('Failed to load shift summary');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Network error occurred');
        });
}

function displayActiveShiftsSummary(summary) {
    document.getElementById('active-shifts-count').textContent = summary.active_shifts || 0;
    document.getElementById('total-sales-sum').textContent = formatCurrency(summary.total_sales);
    document.getElementById('total-payments-sum').textContent = formatCurrency(summary.total_payments);
    document.getElementById('total-debt-sum').textContent = formatCurrency(summary.total_debt);
}

function formatCurrency(amount) {
    return '$' + parseFloat(amount || 0).toFixed(2);
}


// Print function for active shifts report
// Fetch and display report
function fetchAndDisplayActiveShiftsReport() {
    $('#loading-spinner').show();

    $.ajax({
        url: './database/shift_actions.kts.php',
        type: 'GET',
        data: { action: 'get_active_shifts_full_report' },
        dataType: 'json',
        success: function(response) {
            $('#loading-spinner').hide();
            
            console.log('Active Shifts Report Response:', response);

            if (!response || !response.success || !response.data) {
                toastr.error(response?.message || 'Failed to load report');
                return;
            }

            displayFullActiveShiftsReport(response);
        },
        error: function(xhr, status, error) {
            $('#loading-spinner').hide();
            toastr.error('Error loading report: ' + error);
            console.error('Report error:', xhr.responseText);
        }
    });
}

// Display the report in modal
function displayFullActiveShiftsReport(response) {
    if (!response.success) {
        toastr.error(response.message || 'Failed to generate report');
        return;
    }

    const { 
        total_sales, 
        total_received, 
        total_debt, 
        total_expenses,
        cash_at_hand,
        products, 
        payments, 
        expenses,
        generated_at 
    } = response.data;
    
    const formatNumber = (num) => {
        const number = typeof num === 'string' ? parseFloat(num) : num;
        return isNaN(number) ? '0.00' : number.toFixed(2);
    };

    let html = `
        <div class="full-shifts-report">
            <div class="report-header text-center">
                <h4>ACTIVE SHIFTS REPORT</h4>
                <div class="report-date">${new Date(generated_at).toLocaleString()}</div>
            </div>
            
            
                
                <div class="divider"></div>
                
                <h5>PRODUCTS SOLD</h5>
                <table class="thermal-table">
                    <thead>
                        <tr>
                            <th>PRODUCT</th>
                            <th class="text-center">QTY</th>
                            <th class="text-right">AMOUNT</th>
                        </tr>
                    </thead>
                    <tbody>
    `;
    
    products.forEach(product => {
        html += `
            <tr>
                <td>${product.name}</td>
                <td class="text-center">${product.quantity}</td>
                <td class="text-right">${formatNumber(product.total)}</td>
            </tr>
        `;
    });
    
    html += `
                    </tbody>
                </table>
                
                <div class="divider"></div>
                
                <h5>PAYMENTS RECEIVED</h5>
                <table class="thermal-table">
                    <thead>
                        <tr>
                            <th>METHOD</th>
                            <th class="text-right">AMOUNT</th>
                        </tr>
                    </thead>
                    <tbody>
    `;
    
    payments.forEach(payment => {
        html += `
            <tr>
                <td>${payment.method}</td>
                <td class="text-right">${formatNumber(payment.amount)}</td>
            </tr>
        `;
    });
    
    html += `
                    </tbody>
                </table>
                
                <div class="divider"></div>
                
                <h5>EXPENSES</h5>
                <table class="thermal-table">
                    <thead>
                        <tr>
                            <th>DESCRIPTION</th>
                            <th class="text-right">AMOUNT</th>
                            <th class="text-center">DATE</th>
                        </tr>
                    </thead>
                    <tbody>
    `;
    
    expenses.forEach(expense => {
        html += `
            <tr>
                <td>${expense.name}</td>
                <td class="text-right">${formatNumber(expense.amount)}</td>
                <td class="text-center">${new Date(expense.date).toLocaleDateString()}</td>
            </tr>
        `;
    });
    
    html += `
                    </tbody>
                </table>
            </div>
            
            <div class="divider"></div>
           
            
            <div class="totals-section">
                <h5>FINANCIAL SUMMARY</h5>
                <table class="thermal-table">
                    <tr>
                        <th>TOTAL SALES</th>
                        <td class="text-right">${formatNumber(total_sales)}</td>
                    </tr>
                    <tr>
                        <th>TOTAL RECEIVED</th>
                        <td class="text-right">${formatNumber(total_received)}</td>
                    </tr>
                    <tr>
                        <th>TOTAL EXPENSES</th>
                        <td class="text-right">${formatNumber(total_expenses)}</td>
                    </tr>
                    <tr class="total-row">
                        <th>CASH AT HAND</th>
                        <td class="text-right">${formatNumber(cash_at_hand)}</td>
                    </tr>
                    <tr>
                        <th>TOTAL DEBT</th>
                        <td class="text-right">${formatNumber(total_debt)}</td>
                    </tr>
                </table>
                 <div class="divider"></div>
            
            <div class="report-footer text-center">
                <small>Report generated at: ${new Date().toLocaleString()}</small>
            </div>
        </div>
        
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary" onclick="printActiveShiftsReport(true)">Print Thermal</button>
            <button type="button" class="btn btn-info" onclick="printActiveShiftsReport(false)">Print Regular</button>
        </div>
    `;
    
    $('#reportModal .modal-body').html(html);
    $('#reportModal .modal-title').text('Combined Active Shifts Report');
    $('#reportModal').modal('show');
}

function printActiveShiftsReport(isThermal) {
    $('#loading-spinner').show();
    
    const reportContent = $('#reportModal .modal-body').clone();
    const printWindow = window.open('', '_blank', 'width=340,height=600');
    
    const thermalStyles = `
        <style>
            /* Your existing styles here */
        </style>
    `;
    
    const printHtml = `
        <html>
            <head>
                <title>Active Shifts Report</title>
                ${thermalStyles}
            </head>
            <body>
                ${reportContent.html()}
            </body>
        </html>
    `;
    
    printWindow.document.open();
    printWindow.document.write(printHtml);
    printWindow.document.close();

    // Single reliable print handler
    printWindow.onload = function() {
        $('#loading-spinner').hide();
        setTimeout(() => {
            printWindow.print();
            // Optional: Close after printing (may not work in all browsers)
            // setTimeout(() => printWindow.close(), 300);
        }, 200);
    };

    // Fallback in case onload doesn't fire
    setTimeout(() => {
        if (!printWindow.closed) {
            $('#loading-spinner').hide();
            printWindow.print();
        }
    }, 2000);
}

window.printActiveShiftsReport = printActiveShiftsReport;
window.displayFullActiveShiftsReport = displayFullActiveShiftsReport;
window.fetchAndDisplayActiveShiftsReport = fetchAndDisplayActiveShiftsReport;
// Load data when page loads
document.addEventListener('DOMContentLoaded', fetchActiveShiftsSummary);

// Add refresh button functionality
document.getElementById('refresh-summary-btn').addEventListener('click', fetchActiveShiftsSummary);

});
</script>
<script>
    
    $(document).ready(function() {
    // Load cash summary when page loads
    loadCashSummary();

    // Refresh button click handler
    $('#refresh-cash-summary').click(function() {
        loadCashSummary();
    });

    // Function to load cash summary data
    function loadCashSummary() {
    $.ajax({
        url: './database/shift_actions.kts.php',
        type: 'GET',
        data: { action: 'get_cash_summary' },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                updateCashSummaryUI(response.data);
            } else {
                toastr.error(response.message);
            }
        },
        error: function(xhr, status, error) {
            toastr.error('Failed to load cash summary: ' + error);
        }
    });
}

function updateCashSummaryUI(data) {
    const formatCurrency = amount => 'KES:' + parseFloat(amount || 0).toFixed(2);
    
    $('#cash-payments').text(formatCurrency(data.total_cash_payments));
    $('#expected-cash').text(formatCurrency(data.total_expected_cash));
    $('#cash-expenses').text(formatCurrency(data.total_expenses));
    $('#cash-difference').text(formatCurrency(data.cash_difference));
    
    // Highlight difference if there's a discrepancy
    if (Math.abs(data.cash_difference) > 0.01) {
        $('#cash-difference').addClass('text-danger');
    } else {
        $('#cash-difference').removeClass('text-danger');
    }
    
    $('#cash-summary-time').text('Last updated: ' + new Date().toLocaleTimeString());
}
    // Function to update UI with cash summary data
    // Function to fetch and calculate sales data

  
});
</script>
<script>
    
    function updateShiftSalesSummary() {
    fetch('./database/get_sales_data.kts.php')
        .then(response => response.json())
        .then(data => {
            if (data.shift_id) {
                // Update the UI with shift-specific data
                document.getElementById('total-sales').textContent = 
                    'Kes:' + (parseFloat(data.total_sales) || 0).toFixed(2);
                document.getElementById('total-payments').textContent = 
                    'Kes:' + (parseFloat(data.total_payments) || 0).toFixed(2);
                document.getElementById('total-debt').textContent = 
                    'Kes:' + (parseFloat(data.outstanding) || 0).toFixed(2);
                
                // You can also display the shift ID if needed
                console.log(`Current active shift: ${data.shift_id}`);
            } else {
                console.warn('No active shift found');
            }
        })
        .catch(error => {
            console.error('Error fetching shift sales data:', error);
        });
}

// Update on page load and set interval for periodic updates
window.addEventListener('DOMContentLoaded', () => {
    updateShiftSalesSummary();
    // Update every 5 minutes (300000 ms)
    setInterval(updateShiftSalesSummary, 300000);
});
</script>

<script>
    
    document.addEventListener('DOMContentLoaded', function() {
    // Load shift history when page loads
    loadShiftHistory(1);
    
    // Function to load shift history with pagination
    function loadShiftHistory(page) {
        fetch(`database/get_shift_history.kts.php?page=${page}`)
            .then(response => response.json())
            .then(data => {
                renderShiftHistory(data.shifts);
                renderPagination(data.totalPages, page);
            })
            .catch(error => console.error('Error:', error));
    }
    
    // Function to render shift history data
 function renderShiftHistory(shifts) {
    const container = document.getElementById('shift-history-container');
    container.innerHTML = '';
    
    if (shifts.length === 0) {
        container.innerHTML = '<tr><td colspan="9" class="text-center">No shift history found</td></tr>';
        return;
    }
    
    shifts.forEach(shift => {
        // Calculate variance (total_orders - total_payments)
        const variance = shift.total_orders - shift.total_payments;
        const varianceClass = variance > 0 ? 'text-danger' : 'text-success'; // Positive variance = debt (danger)
        const varianceSymbol = variance > 0 ? '+' : ''; // Only show + for positive values
        
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${shift.shift_id}</td>
            <td>${shift.employee_name || 'Employee #' + shift.employee_id}</td>
            <td>${formatDateTime(shift.start_time)}</td>
            <td>${shift.end_time ? formatDateTime(shift.end_time) : 'In Progress'}</td>
            <td>$${shift.total_orders.toFixed(2)}</td>
            <td>$${shift.total_payments.toFixed(2)}</td>
            <td class="${varianceClass}">${varianceSymbol}${variance.toFixed(2)}</td>
            <td><span class="badge ${getStatusBadgeClass(shift.status)}">${shift.status}</span></td>
            <td>
                <button class="btn btn-sm btn-primary view-shift-btn" data-shift-id="${shift.shift_id}">
                    <i class="fas fa-eye"></i> View
                </button>
            </td>
        `;
        container.appendChild(row);
    });
    
    // Add event listeners to view buttons
    document.querySelectorAll('.view-shift-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const shiftId = this.getAttribute('data-shift-id');
            viewShiftDetails(shiftId);
        });
    });
}   // Function to render pagination
    function renderPagination(totalPages, currentPage) {
        const pagination = document.getElementById('shift-history-pagination');
        pagination.innerHTML = '';
        
        // Previous button
        const prevLi = document.createElement('li');
        prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
        prevLi.innerHTML = `<a class="page-link" href="#" aria-label="Previous" data-page="${currentPage - 1}">
            <span aria-hidden="true">&laquo;</span>
        </a>`;
        pagination.appendChild(prevLi);
        
        // Page numbers
        for (let i = 1; i <= totalPages; i++) {
            const li = document.createElement('li');
            li.className = `page-item ${i === currentPage ? 'active' : ''}`;
            li.innerHTML = `<a class="page-link" href="#" data-page="${i}">${i}</a>`;
            pagination.appendChild(li);
        }
        
        // Next button
        const nextLi = document.createElement('li');
        nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
        nextLi.innerHTML = `<a class="page-link" href="#" aria-label="Next" data-page="${currentPage + 1}">
            <span aria-hidden="true">&raquo;</span>
        </a>`;
        pagination.appendChild(nextLi);
        
        // Add event listeners to pagination buttons
        pagination.querySelectorAll('.page-link').forEach(link => {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                const page = parseInt(this.getAttribute('data-page'));
                if (!isNaN(page)) {
                    loadShiftHistory(page);
                }
            });
        });
    }
    
    // Helper function to format date/time
    function formatDateTime(datetimeString) {
        if (!datetimeString) return 'N/A';
        const options = { 
            year: 'numeric', 
            month: 'short', 
            day: 'numeric',
            hour: '2-digit', 
            minute: '2-digit',
            hour12: true
        };
        return new Date(datetimeString).toLocaleString('en-US', options);
    }
    
    // Helper function to get badge class based on status
    function getStatusBadgeClass(status) {
        switch (status.toLowerCase()) {
            case 'completed': return 'bg-success';
            case 'in progress': return 'bg-primary';
            case 'pending': return 'bg-warning';
            case 'cancelled': return 'bg-danger';
            default: return 'bg-secondary';
        }
    }
    
    // Function to view shift details (you can implement this as needed)
    // Function to view shift details
function viewShiftDetails(shiftId) {
    const modal = new bootstrap.Modal(document.getElementById('viewShiftModal'));
    const modalContent = document.getElementById('shiftDetailsContent');
    
    // Show loading spinner
    modalContent.innerHTML = `
        <div class="text-center py-4">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
        </div>
    `;
    
    // Show modal
    modal.show();
    
    // Fetch shift details
    fetch(`database/get_shift_details.kts.php?id=${shiftId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderShiftDetails(data.data);
            } else {
                modalContent.innerHTML = `
                    <div class="alert alert-danger">
                        ${data.message || 'Failed to load shift details'}
                    </div>
                `;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            modalContent.innerHTML = `
                <div class="alert alert-danger">
                    An error occurred while loading shift details
                </div>
            `;
        });
}

// Function to render shift details
function renderShiftDetails(data) {
    const modalContent = document.getElementById('shiftDetailsContent');
    const { shift, transactions, summary } = data;
    
    // Format date/time
    const formatDateTime = (datetimeString) => {
        if (!datetimeString) return 'N/A';
        const options = { 
            year: 'numeric', 
            month: 'short', 
            day: 'numeric',
            hour: '2-digit', 
            minute: '2-digit',
            hour12: true
        };
        return new Date(datetimeString).toLocaleString('en-US', options);
    };
    
    // Format currency
    const formatCurrency = (amount) => {
        return amount !== null ? '$' + parseFloat(amount).toFixed(2) : 'N/A';
    };
    
    // Calculate variance
    const variance = shift.ending_cash !== null ? 
        shift.ending_cash - shift.starting_cash : null;
    
    // Build HTML
    let html = `
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-light">
                        <h6 class="mb-0">Shift Information</h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-6">
                                <p class="mb-1"><strong>Shift ID:</strong></p>
                                <p class="mb-1"><strong>Employee:</strong></p>
                                <p class="mb-1"><strong>Start Time:</strong></p>
                                <p class="mb-1"><strong>End Time:</strong></p>
                                <p class="mb-1"><strong>Status:</strong></p>
                            </div>
                            <div class="col-6">
                                <p class="mb-1">${shift.shift_id}</p>
                                <p class="mb-1">${shift.employee_name || 'N/A'}</p>
                                <p class="mb-1">${formatDateTime(shift.start_time)}</p>
                                <p class="mb-1">${shift.end_time ? formatDateTime(shift.end_time) : 'In Progress'}</p>
                                <p class="mb-1"><span class="badge ${getStatusBadgeClass(shift.status)}">${shift.status}</span></p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-light">
                        <h6 class="mb-0">Cash Summary</h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-6">
                                <p class="mb-1"><strong>Opening Cash:</strong></p>
                                <p class="mb-1"><strong>Closing Cash:</strong></p>
                                <p class="mb-1"><strong>Total Payments:</strong></p>
                                <p class="mb-1"><strong>Variance:</strong></p>
                            </div>
                            <div class="col-6">
                                <p class="mb-1">${formatCurrency(shift.starting_cash)}</p>
                                <p class="mb-1">${formatCurrency(shift.ending_cash)}</p>
                                <p class="mb-1">${formatCurrency(shift.total_payments)}</p>
                                <p class="mb-1 ${variance !== null && variance < 0 ? 'text-danger' : 'text-success'}">
                                    ${variance !== null ? (variance >= 0 ? '+' : '') + formatCurrency(variance) : 'N/A'}
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header bg-light">
                        <h6 class="mb-0">Shift Summary</h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4">
                                <div class="card bg-light">
                                    <div class="card-body text-center">
                                        <h5 class="card-title">Total Sales</h5>
                                        <p class="card-text h4">${formatCurrency(summary.total_sales)}</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="card bg-light">
                                    <div class="card-body text-center">
                                        <h5 class="card-title">Total Received</h5>
                                        <p class="card-text h4">${formatCurrency(summary.total_received)}</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="card bg-light">
                                    <div class="card-body text-center">
                                        <h5 class="card-title">Total Debt</h5>
                                        <p class="card-text h4 ${summary.total_debt > 0 ? 'text-danger' : 'text-success'}">
                                            ${formatCurrency(summary.total_debt)}
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="mt-4">
                            <h6>Payment Methods</h6>
                            <div class="row">
                                ${Object.entries(summary.payment_method_totals).map(([method, amount]) => `
                                    <div class="col-md-3 mb-2">
                                        <div class="card">
                                            <div class="card-body p-2">
                                                <p class="mb-0"><strong>${method}:</strong> ${formatCurrency(amount)}</p>
                                            </div>
                                        </div>
                                    </div>
                                `).join('')}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="card">
            <div class="card-header bg-light">
                <h6 class="mb-0">Transactions</h6>
            </div>
            <div class="card-body">
                <div class="accordion" id="transactionsAccordion">
                    ${transactions.map((trans, index) => `
                        <div class="accordion-item">
                            <h2 class="accordion-header" id="heading${index}">
                                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" 
                                    data-bs-target="#collapse${index}" aria-expanded="false" aria-controls="collapse${index}">
                                    <div class="d-flex justify-content-between w-100">
                                        <span>Transaction #${trans.trans_id}</span>
                                        <span class="me-3">${formatDateTime(trans.created_at)}</span>
                                        <span class="badge bg-primary">${formatCurrency(trans.total)}</span>
                                    </div>
                                </button>
                            </h2>
                            <div id="collapse${index}" class="accordion-collapse collapse" aria-labelledby="heading${index}" 
                                data-bs-parent="#transactionsAccordion">
                                <div class="accordion-body">
                                    <div class="row">
                                        <div class="col-md-8">
                                            <h6>Items</h6>
                                            <table class="table table-sm">
                                                <thead>
                                                    <tr>
                                                        <th>Product</th>
                                                        <th>Qty</th>
                                                        <th>Price</th>
                                                        <th>Subtotal</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    ${trans.items.map(item => `
                                                        <tr>
                                                            <td>${item.product_name}</td>
                                                            <td>${item.quantity}</td>
                                                            <td>${formatCurrency(item.selling_price)}</td>
                                                            <td>${formatCurrency(item.subtotal)}</td>
                                                        </tr>
                                                    `).join('')}
                                                </tbody>
                                            </table>
                                        </div>
                                        <div class="col-md-4">
                                            <h6>Payments</h6>
                                            <table class="table table-sm">
                                                <thead>
                                                    <tr>
                                                        <th>Method</th>
                                                        <th>Amount</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    ${trans.payments.map(payment => `
                                                        <tr>
                                                            <td>${payment.payment_method}</td>
                                                            <td>${formatCurrency(payment.amount)}</td>
                                                        </tr>
                                                    `).join('')}
                                                    <tr class="table-secondary">
                                                        <td><strong>Total Received</strong></td>
                                                        <td><strong>${formatCurrency(trans.amount_received)}</strong></td>
                                                    </tr>
                                                    <tr class="table-secondary">
                                                        <td><strong>Total</strong></td>
                                                        <td><strong>${formatCurrency(trans.total)}</strong></td>
                                                    </tr>
                                                    <tr class="${trans.total - trans.amount_received > 0 ? 'table-danger' : 'table-success'}">
                                                        <td><strong>Balance</strong></td>
                                                        <td><strong>${formatCurrency(trans.total - trans.amount_received)}</strong></td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `).join('')}
                </div>
            </div>
        </div>
    `;
    
    modalContent.innerHTML = html;
    
    // Add print functionality
    document.getElementById('printShiftBtn').onclick = function() {
        const printContent = modalContent.innerHTML;
        const originalContent = document.body.innerHTML;
        
        document.body.innerHTML = `
            <div class="container mt-3">
                <h3 class="text-center mb-4">Shift #${shift.shift_id} Report</h3>
                ${printContent}
                <div class="mt-4 text-muted small text-center">
                    Printed on ${new Date().toLocaleString()}
                </div>
            </div>
        `;
        
        window.print();
        document.body.innerHTML = originalContent;
        modal.show(); // Re-show the modal after printing
    };
}

// Helper function for status badge classes
function getStatusBadgeClass(status) {
    switch (status.toLowerCase()) {
        case 'completed': return 'bg-success';
        case 'in progress': return 'bg-primary';
        case 'pending': return 'bg-warning';
        case 'cancelled': return 'bg-danger';
        default: return 'bg-secondary';
    }
}
});
</script>
</body>
</html>