<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header("Location: ../index.php");
    exit();
}

// Allow all logged-in users to access daily summary (including cashiers)
// Daily summary is considered essential operational information

include '../config.php';
date_default_timezone_set('Asia/Colombo');

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Get selected date or default to today
$selected_date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Daily Sales Summary - Dilrukshi Tex</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { background-color: #f8f9fa; }
        .summary-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .metric-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            text-align: center;
            margin-bottom: 20px;
        }
        .metric-value {
            font-size: 2rem;
            font-weight: bold;
            color: #495057;
        }
        .metric-label {
            color: #6c757d;
            font-size: 0.9rem;
            margin-top: 5px;
        }
        .cash-color { border-left: 5px solid #28a745; }
        .card-color { border-left: 5px solid #007bff; }
        .refund-color { border-left: 5px solid #dc3545; }
        .total-color { border-left: 5px solid #6f42c1; }
        @media print {
            .no-print { display: none !important; }
            body { background: white !important; }
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <!-- Header -->
        <div class="row mb-4 no-print">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center">
                    <h2><i class="fas fa-chart-line me-2"></i>Daily Sales Summary</h2>
                    <div>
                        <?php if ($_SESSION['role'] === 'cashier'): ?>
                        <a href="../dashboard.php" class="btn btn-secondary me-2">
                            <i class="fas fa-arrow-left"></i> Back to Dashboard
                        </a>
                        <?php endif; ?>
                        <a href="daily_summary_compact.php?date=<?php echo $selected_date; ?>" class="btn btn-info me-2">
                            <i class="fas fa-print"></i> Compact Print
                        </a>
                        <button onclick="window.print()" class="btn btn-primary">
                            <i class="fas fa-print"></i> Full Print
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Date Selection -->
        <div class="row mb-4 no-print">
            <div class="col-md-4">
                <form method="GET" class="d-flex">
                    <input type="date" name="date" class="form-control me-2" value="<?php echo $selected_date; ?>">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-search"></i> View
                    </button>
                </form>
            </div>
        </div>

        <!-- Summary Header -->
        <div class="row">
            <div class="col-12">
                <div class="summary-card">
                    <div class="row align-items-center">
                        <div class="col-md-6">
                            <h3><i class="fas fa-calendar-day me-2"></i>End of Day Trading Summary</h3>
                            <h4><?php echo date('F j, Y', strtotime($selected_date)); ?></h4>
                            <p class="mb-0">Business Day Closure Report</p>
                        </div>
                        <div class="col-md-6 text-end">
                            <h5>TRX Tile POS System</h5>
                            <p class="mb-0">Generated: <?php echo date('Y-m-d H:i:s'); ?></p>
                            <p class="mb-0">Printed by: <?php echo $_SESSION['username']; ?></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <?php
        // Get daily sales data with error handling
        try {
             // Get opening cash for the selected date
            $stmt = $conn->prepare("SELECT amount FROM opening_cash WHERE cash_date = ?");
            $stmt->bind_param("s", $selected_date);
            $stmt->execute();
            $opening_cash_row = $stmt->get_result()->fetch_assoc();
            $opening_cash = $opening_cash_row ? floatval($opening_cash_row['amount']) : 0;

            // Cash sales
            $cash_sales_query = "SELECT COUNT(*) as count, COALESCE(SUM(total_amount), 0) as total 
                               FROM sales 
                               WHERE DATE(sale_date) = ? AND payment_method = 'cash'";
            $stmt = $conn->prepare($cash_sales_query);
            $stmt->bind_param("s", $selected_date);
            $stmt->execute();
            $cash_result = $stmt->get_result()->fetch_assoc();

            // Card sales
            $card_sales_query = "SELECT COUNT(*) as count, COALESCE(SUM(total_amount), 0) as total 
                               FROM sales 
                               WHERE DATE(sale_date) = ? AND payment_method = 'card'";
            $stmt = $conn->prepare($card_sales_query);
            $stmt->bind_param("s", $selected_date);
            $stmt->execute();
            $card_result = $stmt->get_result()->fetch_assoc();

            // Voucher sales (including split payments)
            // 1. Pure voucher payments
            $voucher_sales_query = "SELECT COUNT(*) as count, COALESCE(SUM(voucher_amount), 0) as total_voucher, COALESCE(SUM(total_amount), 0) as total 
                               FROM sales 
                               WHERE DATE(sale_date) = ? AND payment_method = 'voucher'";
            $stmt = $conn->prepare($voucher_sales_query);
            $stmt->bind_param("s", $selected_date);
            $stmt->execute();
            $voucher_result = $stmt->get_result()->fetch_assoc();

            // 2. Split payments: voucher + cash/card
            // Assumes sales table has voucher_amount, secondary_payment_method, secondary_amount columns
            $split_voucher_query = "SELECT COUNT(*) as count, COALESCE(SUM(voucher_amount), 0) as total_voucher, COALESCE(SUM(secondary_amount), 0) as total_secondary, secondary_payment_method 
                                    FROM sales 
                                    WHERE DATE(sale_date) = ? AND payment_method = 'voucher' AND secondary_payment_method IS NOT NULL
                                    GROUP BY secondary_payment_method";
            $stmt = $conn->prepare($split_voucher_query);
            $stmt->bind_param("s", $selected_date);
            $stmt->execute();
            $split_voucher_results = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

            // Aggregate split voucher payments into cash/card totals
            $split_cash_total = 0;
            $split_card_total = 0;
            foreach ($split_voucher_results as $row) {
                if ($row['secondary_payment_method'] === 'cash') {
                    $split_cash_total += $row['total_secondary'];
                } elseif ($row['secondary_payment_method'] === 'card') {
                    $split_card_total += $row['total_secondary'];
                }
            }

            // Add split voucher secondary payments to cash/card sales
            $cash_result['total'] += $split_cash_total;
            $card_result['total'] += $split_card_total;

            // Add split voucher transactions to cash/card counts (optional, if you want to count them)
            $cash_result['count'] += array_sum(array_map(function($row) { return ($row['secondary_payment_method'] === 'cash') ? $row['count'] : 0; }, $split_voucher_results));
            $card_result['count'] += array_sum(array_map(function($row) { return ($row['secondary_payment_method'] === 'card') ? $row['count'] : 0; }, $split_voucher_results));

            // Add split voucher voucher_amount to voucher total
            $voucher_result['total'] += array_sum(array_map(function($row) { return $row['total_voucher']; }, $split_voucher_results));
            $voucher_result['count'] += array_sum(array_map(function($row) { return $row['count']; }, $split_voucher_results));

            // Get refunds (try exchange_log table, fallback if it doesn't exist)
            $refund_result = ['count' => 0, 'total' => 0];
            try {
                $refund_query = "SELECT COUNT(*) as count, COALESCE(SUM(ABS(price_difference)), 0) as total 
                                FROM exchange_log 
                                WHERE DATE(exchange_date) = ? AND price_difference < 0";
                $stmt = $conn->prepare($refund_query);
                $stmt->bind_param("s", $selected_date);
                $stmt->execute();
                $refund_result = $stmt->get_result()->fetch_assoc();
            } catch (Exception $e) {
                // exchange_log table doesn't exist, use default values
                $refund_result = ['count' => 0, 'total' => 0];
            }

            // Get total items sold
            $items_query = "SELECT COALESCE(SUM(si.quantity), 0) as total_items 
                           FROM sale_items si 
                           JOIN sales s ON si.sale_id = s.id 
                           WHERE DATE(s.sale_date) = ?";
            $stmt = $conn->prepare($items_query);
            $stmt->bind_param("s", $selected_date);
            $stmt->execute();
            $items_result = $stmt->get_result()->fetch_assoc();

            // Get opening cash (if you track this)
            $opening_cash = 0; // You can modify this to track opening cash balance

            // Get cash sales details
            $cash_breakdown_query = "SELECT 
                COUNT(*) as transactions,
                COALESCE(SUM(total_amount), 0) as total_sales,
                COALESCE(SUM(paid_amount), 0) as total_received,
                COALESCE(SUM(paid_amount - total_amount), 0) as total_change_given
                FROM sales 
                WHERE DATE(sale_date) = ? AND payment_method = 'cash'";
            $stmt = $conn->prepare($cash_breakdown_query);
            $stmt->bind_param("s", $selected_date);
            $stmt->execute();
            $cash_breakdown = $stmt->get_result()->fetch_assoc();

            // Add voucher split cash payments to cash received and expected in till
            $voucher_cash_query = "SELECT COALESCE(SUM(secondary_amount), 0) as voucher_cash_total FROM sales WHERE DATE(sale_date) = ? AND payment_method = 'voucher' AND secondary_payment_method = 'cash'";
            $stmt = $conn->prepare($voucher_cash_query);
            $stmt->bind_param("s", $selected_date);
            $stmt->execute();
            $voucher_cash_result = $stmt->get_result()->fetch_assoc();
            $voucher_cash_total = $voucher_cash_result['voucher_cash_total'] ?? 0;
            $cash_breakdown['total_received'] += $voucher_cash_total;

            // Get daily expenses
            $expenses_total = 0;
            $expenses_breakdown = [];
            $cash_expenses = 0;
            
            // Check if expenses table exists
            $table_check = $conn->query("SHOW TABLES LIKE 'expenses'");
            if ($table_check && $table_check->num_rows > 0) {
                // Get total expenses for the day
                $expenses_query = "SELECT 
                    COUNT(*) as expense_count,
                    COALESCE(SUM(amount), 0) as total_expenses,
                    COALESCE(SUM(CASE WHEN payment_method = 'cash' THEN amount ELSE 0 END), 0) as cash_expenses
                    FROM expenses 
                    WHERE DATE(expense_date) = ?";
                $stmt = $conn->prepare($expenses_query);
                $stmt->bind_param("s", $selected_date);
                $stmt->execute();
                $expenses_result = $stmt->get_result()->fetch_assoc();
                
                $expenses_total = $expenses_result['total_expenses'];
                $cash_expenses = $expenses_result['cash_expenses'];
                
                // Get expenses breakdown by category
                $expenses_breakdown_query = "SELECT 
                    category,
                    COUNT(*) as count,
                    SUM(amount) as total,
                    payment_method
                    FROM expenses 
                    WHERE DATE(expense_date) = ?
                    GROUP BY category, payment_method
                    ORDER BY total DESC";
                $stmt = $conn->prepare($expenses_breakdown_query);
                $stmt->bind_param("s", $selected_date);
                $stmt->execute();
                $expenses_breakdown = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            }

            // Get hourly sales for trend analysis
            $hourly_query = "SELECT 
                HOUR(sale_date) as hour,
                COUNT(*) as transactions,
                SUM(total_amount) as hourly_total
                FROM sales 
                WHERE DATE(sale_date) = ?
                GROUP BY HOUR(sale_date)
                ORDER BY hour";
            $stmt = $conn->prepare($hourly_query);
            $stmt->bind_param("s", $selected_date);
            $stmt->execute();
            $hourly_sales = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

            // Calculate cash till totals (including expenses)
            // Cash received = cash sales paid_amount + voucher split cash payments
            $cash_received = $cash_breakdown['total_received'];
            // Expected in till = opening cash + cash received - change given - cash expenses
            $expected_cash_in_till = $opening_cash + $cash_received - $cash_breakdown['total_change_given'] - $cash_expenses;
            $net_cash_position = $expected_cash_in_till;
            
            // Calculate totals
            $total_transactions = $cash_result['count'] + $card_result['count'] + $voucher_result['count'];
            $total_sales_amount = $cash_result['total'] + $card_result['total'] + $voucher_result['total'];
            $net_sales = $total_sales_amount - $refund_result['total'];
            
        } catch (Exception $e) {
            // If there's any error, set default values
            $cash_result = ['count' => 0, 'total' => 0];
            $card_result = ['count' => 0, 'total' => 0];
            $refund_result = ['count' => 0, 'total' => 0];
            $items_result = ['total_items' => 0];
            $cash_breakdown = ['transactions' => 0, 'total_sales' => 0, 'total_received' => 0, 'total_change_given' => 0];
            $hourly_sales = [];
            $opening_cash = 0;
            $expected_cash_in_till = 0;
            $total_transactions = 0;
            $total_sales_amount = 0;
            $net_sales = 0;
            
            echo "<div class='alert alert-danger'>Error loading sales data: " . $e->getMessage() . "</div>";
        }
        ?>

        <!-- Metrics Cards -->
        <div class="row">
            <!-- Cash Sales -->
            <div class="col-md-3">
                <div class="metric-card cash-color">
                    <div class="metric-value text-success">
                        <i class="fas fa-money-bill-wave"></i>
                        Rs. <?php echo number_format($cash_result['total'], 2); ?>
                    </div>
                    <div class="metric-label">Cash Sales</div>
                    <div class="text-muted mt-2"><?php echo $cash_result['count']; ?> transactions</div>
                </div>
            </div>

            <!-- Card Sales -->
            <div class="col-md-3">
                <div class="metric-card card-color">
                    <div class="metric-value text-primary">
                        <i class="fas fa-credit-card"></i>
                        Rs. <?php echo number_format($card_result['total'], 2); ?>
                    </div>
                    <div class="metric-label">Card Sales</div>
                    <div class="text-muted mt-2"><?php echo $card_result['count']; ?> transactions</div>
                </div>
            </div>

            <!-- Voucher Sales -->
            <div class="col-md-3">
                <div class="metric-card" style="border-left: 5px solid #ffc107;">
                    <div class="metric-value text-warning">
                        <i class="fas fa-ticket-alt"></i>
                        Rs. <?php echo number_format($voucher_result['total'], 2); ?>
                    </div>
                    <div class="metric-label">Voucher Sales</div>
                    <div class="text-muted mt-2"><?php echo $voucher_result['count']; ?> transactions</div>
                </div>
            </div>

            <!-- Refunds -->
            <div class="col-md-3">
                <div class="metric-card refund-color">
                    <div class="metric-value text-danger">
                        <i class="fas fa-undo"></i>
                        Rs. <?php echo number_format($refund_result['total'], 2); ?>
                    </div>
                    <div class="metric-label">Refunds</div>
                    <div class="text-muted mt-2"><?php echo $refund_result['count']; ?> refunds</div>
                </div>
            </div>

            <!-- Total Items -->
            <div class="col-md-3">
                <div class="metric-card total-color">
                    <div class="metric-value text-purple">
                        <i class="fas fa-boxes"></i>
                        <?php echo number_format($items_result['total_items']); ?>
                    </div>
                    <div class="metric-label">Items Sold</div>
                    <div class="text-muted mt-2">Total quantity</div>
                </div>
            </div>
        </div>

        <!-- Expenses & Net Position Cards -->
        <?php if ($expenses_total > 0): ?>
        <div class="row">
            <!-- Total Expenses -->
            <div class="col-md-3">
                <div class="metric-card" style="border-left: 5px solid #dc3545;">
                    <div class="metric-value text-danger">
                        <i class="fas fa-receipt"></i>
                        Rs. <?php echo number_format($expenses_total, 2); ?>
                    </div>
                    <div class="metric-label">Total Expenses</div>
                    <div class="text-muted mt-2"><?php echo array_sum(array_column($expenses_breakdown, 'count')); ?> transactions</div>
                </div>
            </div>

            <!-- Cash Expenses -->
            <div class="col-md-3">
                <div class="metric-card" style="border-left: 5px solid #fd7e14;">
                    <div class="metric-value text-warning">
                        <i class="fas fa-money-bill-wave"></i>
                        Rs. <?php echo number_format($cash_expenses, 2); ?>
                    </div>
                    <div class="metric-label">Cash Expenses</div>
                    <div class="text-muted mt-2">Paid from till</div>
                </div>
            </div>

            <!-- Net Revenue -->
            <div class="col-md-3">
                <div class="metric-card" style="border-left: 5px solid #198754;">
                    <div class="metric-value text-success">
                        <i class="fas fa-chart-line"></i>
                        Rs. <?php echo number_format($total_sales_amount - $expenses_total, 2); ?>
                    </div>
                    <div class="metric-label">Net Revenue</div>
                    <div class="text-muted mt-2">After expenses</div>
                </div>
            </div>

            <!-- Cash in Till -->
            <div class="col-md-3">
                <div class="metric-card" style="border-left: 5px solid #0dcaf0;">
                    <div class="metric-value text-info">
                        <i class="fas fa-cash-register"></i>
                        Rs. <?php echo number_format($net_cash_position, 2); ?>
                    </div>
                    <div class="metric-label">Cash in Till</div>
                    <div class="text-muted mt-2">Expected amount</div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Summary Table -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-table me-2"></i>Daily Summary Breakdown</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Payment Method</th>
                                        <th>Transactions</th>
                                        <th>Amount</th>
                                        <th>Percentage</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td><i class="fas fa-money-bill-wave text-success me-2"></i>Cash</td>
                                        <td><?php echo $cash_result['count']; ?></td>
                                        <td>Rs. <?php echo number_format($cash_result['total'], 2); ?></td>
                                        <td><?php echo $total_sales_amount > 0 ? number_format(($cash_result['total'] / $total_sales_amount) * 100, 1) : 0; ?>%</td>
                                    </tr>
                                    <tr>
                                        <td><i class="fas fa-credit-card text-primary me-2"></i>Card</td>
                                        <td><?php echo $card_result['count']; ?></td>
                                        <td>Rs. <?php echo number_format($card_result['total'], 2); ?></td>
                                        <td><?php echo $total_sales_amount > 0 ? number_format(($card_result['total'] / $total_sales_amount) * 100, 1) : 0; ?>%</td>
                                    </tr>
                                    <tr>
                                        <td><i class="fas fa-ticket-alt text-warning me-2"></i>Voucher</td>
                                        <td><?php echo $voucher_result['count']; ?></td>
                                        <td>Rs. <?php echo number_format($voucher_result['total'], 2); ?></td>
                                        <td><?php echo $total_sales_amount > 0 ? number_format(($voucher_result['total'] / $total_sales_amount) * 100, 1) : 0; ?>%</td>
                                    </tr>
                                    <tr class="table-warning">
                                        <td><strong><i class="fas fa-calculator me-2"></i>Total Sales</strong></td>
                                        <td><strong><?php echo $total_transactions; ?></strong></td>
                                        <td><strong>Rs. <?php echo number_format($total_sales_amount, 2); ?></strong></td>
                                        <td><strong>100%</strong></td>
                                    </tr>
                                    
                                    <!-- Expenses Section -->
                                    <?php if ($expenses_total > 0): ?>
                                    <tr class="table-danger">
                                        <td><i class="fas fa-receipt text-danger me-2"></i>Total Expenses</td>
                                        <td><?php echo array_sum(array_column($expenses_breakdown, 'count')); ?></td>
                                        <td>-Rs. <?php echo number_format($expenses_total, 2); ?></td>
                                        <td class="text-danger"><?php echo $total_sales_amount > 0 ? number_format(($expenses_total / $total_sales_amount) * 100, 1) : 0; ?>%</td>
                                    </tr>
                                    <tr class="table-danger">
                                        <td><i class="fas fa-money-bill-wave text-danger me-2"></i>Cash Expenses</td>
                                        <td>-</td>
                                        <td>-Rs. <?php echo number_format($cash_expenses, 2); ?></td>
                                        <td class="text-danger">Cash Only</td>
                                    </tr>
                                    <?php endif; ?>
                                    
                                    <!-- Net Totals -->
                                    <tr class="table-success">
                                        <td><strong><i class="fas fa-hand-holding-usd text-success me-2"></i>Net Revenue</strong></td>
                                        <td><strong>-</strong></td>
                                        <td><strong>Rs. <?php echo number_format($total_sales_amount - $expenses_total, 2); ?></strong></td>
                                        <td><strong>Net</strong></td>
                                    </tr>
                                    <tr class="table-info">
                                        <td><strong><i class="fas fa-cash-register text-info me-2"></i>Cash in Till</strong></td>
                                        <td><strong>-</strong></td>
                                        <td><strong>Rs. <?php echo number_format($net_cash_position, 2); ?></strong></td>
                                        <td><strong>After Expenses</strong></td>
                                    </tr>
                                    <tr class="table-danger">
                                        <td><i class="fas fa-undo text-danger me-2"></i>Refunds</td>
                                        <td><?php echo $refund_result['count']; ?></td>
                                        <td>- Rs. <?php echo number_format($refund_result['total'], 2); ?></td>
                                        <td>-</td>
                                    </tr>
                                    <tr class="table-success">
                                        <td><strong><i class="fas fa-coins me-2"></i>Net Sales</strong></td>
                                        <td><strong><?php echo $total_transactions; ?></strong></td>
                                        <td><strong>Rs. <?php echo number_format($net_sales, 2); ?></strong></td>
                                        <td><strong>Net</strong></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Expenses Breakdown -->
        <?php if (!empty($expenses_breakdown)): ?>
        <div class="row mt-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header bg-danger text-white">
                        <h5><i class="fas fa-list me-2"></i>Daily Expenses Breakdown</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Category</th>
                                        <th>Payment Method</th>
                                        <th>Count</th>
                                        <th>Amount</th>
                                        <th>Impact on Cash</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($expenses_breakdown as $expense): ?>
                                    <tr>
                                        <td>
                                            <i class="fas fa-tag text-secondary me-2"></i>
                                            <?php echo htmlspecialchars($expense['category']); ?>
                                        </td>
                                        <td>
                                            <span class="badge <?php echo $expense['payment_method'] == 'cash' ? 'bg-success' : ($expense['payment_method'] == 'card' ? 'bg-primary' : 'bg-info'); ?>">
                                                <?php echo ucfirst(str_replace('_', ' ', $expense['payment_method'])); ?>
                                            </span>
                                        </td>
                                        <td><?php echo $expense['count']; ?></td>
                                        <td class="text-danger">Rs. <?php echo number_format($expense['total'], 2); ?></td>
                                        <td>
                                            <?php if ($expense['payment_method'] == 'cash'): ?>
                                                <span class="text-danger">
                                                    <i class="fas fa-minus-circle"></i> Reduces Cash Till
                                                </span>
                                            <?php else: ?>
                                                <span class="text-muted">
                                                    <i class="fas fa-check-circle"></i> No Cash Impact
                                                </span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Additional Statistics -->
        <div class="row mt-4">
            <!-- Cash Till Reconciliation -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-success text-white">
                        <h6><i class="fas fa-cash-register me-2"></i>Cash Till Reconciliation</h6>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm mb-0">
                            <tr>
                                <td>Opening Cash:</td>
                                <td class="text-end">Rs. <?php echo number_format($opening_cash, 2); ?></td>
                            </tr>
                            <tr>
                                <td>Cash Sales:</td>
                                <td class="text-end">Rs. <?php echo number_format($cash_breakdown['total_sales'], 2); ?></td>
                            </tr>
                            <tr>
                                <td>Cash Received:</td>
                                <td class="text-end">Rs. <?php echo number_format($cash_breakdown['total_received'], 2); ?></td>
                            </tr>
                         
                            <tr class="text-danger">
                                <td>Cash Expenses:</td>
                                <td class="text-end">-Rs. <?php echo number_format($cash_expenses, 2); ?></td>
                            </tr>
                            <tr class="table-warning">
                                <td><strong>Expected in Till:</strong></td>
                                <td class="text-end"><strong>Rs. <?php echo number_format($net_cash_position, 2); ?></strong></td>
                            </tr>
                            <tr>
                                <td>Actual Count:</td>
                                <td class="text-end">Rs. _____________</td>
                            </tr>
                            <tr>
                                <td>Difference:</td>
                                <td class="text-end">Rs. _____________</td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Daily Performance -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-info text-white">
                        <h6><i class="fas fa-chart-line me-2"></i>Daily Performance</h6>
                    </div>
                    <div class="card-body">
                        <div class="row text-center">
                            <div class="col-6">
                                <div class="metric-value text-success" style="font-size: 1.2rem;">
                                    <?php echo $total_transactions; ?>
                                </div>
                                <div class="metric-label">Total Transactions</div>
                            </div>
                            <div class="col-6">
                                <div class="metric-value text-primary" style="font-size: 1.2rem;">
                                    <?php echo number_format($items_result['total_items']); ?>
                                </div>
                                <div class="metric-label">Items Sold</div>
                            </div>
                        </div>
                        <hr>
                        <div class="row text-center">
                            <div class="col-6">
                                <div class="metric-value text-info" style="font-size: 1.2rem;">
                                    Rs. <?php echo $total_transactions > 0 ? number_format($total_sales_amount / $total_transactions, 2) : '0.00'; ?>
                                </div>
                                <div class="metric-label">Avg Transaction</div>
                            </div>
                            <div class="col-6">
                                <div class="metric-value text-warning" style="font-size: 1.2rem;">
                                    <?php echo $total_transactions > 0 ? number_format($items_result['total_items'] / $total_transactions, 1) : '0'; ?>
                                </div>
                                <div class="metric-label">Items/Transaction</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Hourly Sales Trend -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h6><i class="fas fa-clock me-2"></i>Hourly Sales Breakdown</h6>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>Hour</th>
                                        <th>Transactions</th>
                                        <th>Sales Amount</th>
                                        <th>% of Daily Sales</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($hourly_sales)): ?>
                                        <tr><td colspan="4" class="text-center">No sales recorded for this day</td></tr>
                                    <?php else: ?>
                                        <?php foreach ($hourly_sales as $hour_data): ?>
                                            <tr>
                                                <td><?php echo sprintf('%02d:00 - %02d:59', $hour_data['hour'], $hour_data['hour']); ?></td>
                                                <td><?php echo $hour_data['transactions']; ?></td>
                                                <td>Rs. <?php echo number_format($hour_data['hourly_total'], 2); ?></td>
                                                <td><?php echo $total_sales_amount > 0 ? number_format(($hour_data['hourly_total'] / $total_sales_amount) * 100, 1) : 0; ?>%</td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- End of Day Checklist -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header bg-dark text-white">
                        <h6><i class="fas fa-tasks me-2"></i>End of Day Checklist</h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="check1">
                                    <label class="form-check-label" for="check1">Cash till counted and reconciled</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="check2">
                                    <label class="form-check-label" for="check2">All receipts filed properly</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="check3">
                                    <label class="form-check-label" for="check3">Stock levels checked</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="check4">
                                    <label class="form-check-label" for="check4">Equipment turned off</label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="check5">
                                    <label class="form-check-label" for="check5">Daily sales report printed</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="check6">
                                    <label class="form-check-label" for="check6">Backup completed</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="check7">
                                    <label class="form-check-label" for="check7">Store secured</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="check8">
                                    <label class="form-check-label" for="check8">Manager/Owner notified</label>
                                </div>
                            </div>
                        </div>
                        <hr>
                        <div class="row">
                            <div class="col-md-6">
                                <label class="form-label">Closing Staff Signature:</label>
                                <div style="border-bottom: 1px solid #000; height: 30px; margin-top: 10px;"></div>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Manager/Supervisor Signature:</label>
                                <div style="border-bottom: 1px solid #000; height: 30px; margin-top: 10px;"></div>
                            </div>
                        </div>
                        
                        <!-- Print Controls -->
                        <div class="row mt-4 no-print">
                            <div class="col-12 text-center">
                                <button onclick="window.print()" class="btn btn-primary btn-lg me-3">
                                    <i class="fas fa-print"></i> Print Daily Summary
                                </button>
                                <a href="daily_summary_compact.php?date=<?= $selected_date ?>" class="btn btn-secondary btn-lg me-3" target="_blank">
                                    <i class="fas fa-receipt"></i> Thermal Print
                                </a>
                                <?php if ($_SESSION['role'] === 'cashier'): ?>
                                <a href="../dashboard.php" class="btn btn-outline-secondary">
                                    <i class="fas fa-arrow-left"></i> Back to Dashboard
                                </a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <style>
        @media print {
            .no-print {
                display: none !important;
            }
            
            .container-fluid {
                margin: 0;
                padding: 0;
            }
            
            .card {
                border: none;
                box-shadow: none;
            }
            
            body {
                font-size: 12px;
            }
            
            .navbar {
                display: none;
            }
        }
    </style>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
