<?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');

// Get selected date or default to today
$selected_date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');

// 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;

    // Voucher sales (including split 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();

    // Split payments: voucher + cash/card
    $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);

    $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
    $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 cash sales paid_amount
    $cash_paid_query = "SELECT COUNT(*) as count, COALESCE(SUM(total_amount), 0) as total, COALESCE(SUM(paid_amount), 0) as paid_total, COALESCE(SUM(paid_amount - total_amount), 0) as change_given FROM sales WHERE DATE(sale_date) = ? AND payment_method = 'cash'";
    $stmt = $conn->prepare($cash_paid_query);
    $stmt->bind_param("s", $selected_date);
    $stmt->execute();
    $cash_result = $stmt->get_result()->fetch_assoc();

    // Add voucher split cash payments
    $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_received = $cash_result['paid_total'] + $voucher_cash_total;
    $change_given = $cash_result['change_given'];

    // 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_result['total'] += $voucher_cash_total;

    $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();

    // 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();

    // Calculate totals
    $total_transactions = $cash_result['count'] + $card_result['count'];
    $total_sales_amount = $cash_result['total'] + $card_result['total'];

    // Get expenses data
    $expenses_query = "SELECT 
                        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();

    // Get detailed expenses information
    $expenses_detail_query = "SELECT category, payment_method, amount, description, 
                             DATE_FORMAT(expense_date, '%H:%i') as expense_time,
                             DATE_FORMAT(expense_date, '%d/%m/%Y') as expense_date_formatted
                             FROM expenses 
                             WHERE DATE(expense_date) = ?
                             ORDER BY expense_date ASC";
    $stmt = $conn->prepare($expenses_detail_query);
    $stmt->bind_param("s", $selected_date);
    $stmt->execute();
    $expenses_detail = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    
} catch (Exception $e) {
    // If there's any error, set default values
    $cash_result = ['count' => 0, 'total' => 0];
    $card_result = ['count' => 0, 'total' => 0];
    $items_result = ['total_items' => 0];
    $expenses_result = ['total_expenses' => 0, 'cash_expenses' => 0];
    $expenses_detail = [];
    $total_transactions = 0;
    $total_sales_amount = 0;
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Daily Summary - <?= $selected_date ?></title>
    <style>
        body { 
            font-family: 'Courier New', monospace; 
            font-size: 15px;
            margin: 0; 
            padding: 5px;
            width: 58mm;
            font-weight: bold;
            line-height: 1.3;
        }
        .summary { width: 100%; }
        .center { text-align: center; }
        .line { border-bottom: 1px dashed #000; margin: 5px 0; }
        .solid-line { border-bottom: 2px solid #000; margin: 5px 0; }
        .row { 
            display: flex; 
            justify-content: space-between; 
            margin: 3px 0;
            font-size: 14px;
        }
        .total-row { 
            display: flex; 
            justify-content: space-between; 
            font-weight: bold;
            font-size: 16px;
        }
        .small { font-size: 13px; }
        .bold { font-weight: bold; font-size: 16px; }
        .header { font-size: 17px; font-weight: bold; }
        @media print { 
            .no-print { display: none; }
            body { margin: 0; }
        }
    </style>
</head>
<body>
    <div class="summary">
        <!-- Header -->
        <div class="center">
            <div class="header">DAILY SUMMARY</div>
            <div class="small">Dilrukshi Tex</div>
            <div class="small"><?= date('d M Y', strtotime($selected_date)) ?></div>
        </div>
        <div class="solid-line"></div>
        
        <!-- Date & Time -->
        <div class="small">
            <div>Trading Date: <?= date('d/m/Y', strtotime($selected_date)) ?></div>
            <div>Generated: <?= date('d/m/Y H:i') ?></div>
            <div>By: <?= $_SESSION['username'] ?></div>
        </div>
        <div class="line"></div>
        
        <!-- Sales Summary -->
        <div class="center bold small">SALES BREAKDOWN</div>

        <div class="row">
            <span>Voucher Sales:</span>
            <span><?= $voucher_result['count'] ?> sales</span>
        </div>
        <div class="row">
            <span></span>
            <span>Rs <?= number_format($voucher_result['total'], 2) ?></span>
        </div>
        
        <div class="row">
            <span>Cash Sales:</span>
            <span><?= $cash_result['count'] ?> sales</span>
        </div>
        <div class="row">
            <span></span>
            <span>Rs <?= number_format($cash_result['total'], 2) ?></span>
        </div>
        
        <div class="row">
            <span>Card Sales:</span>
            <span><?= $card_result['count'] ?> sales</span>
        </div>
        <div class="row">
            <span></span>
            <span>Rs <?= number_format($card_result['total'], 2) ?></span>
        </div>
        
        <div class="line"></div>
        
        <!-- Totals -->
        <div class="total-row">
            <span>TOTAL SALES:</span>
            <span>Rs <?= number_format($total_sales_amount, 2) ?></span>
        </div>
        
        <div class="row">
            <span>Total Transactions:</span>
            <span><?= $total_transactions ?></span>
        </div>
        
        <div class="row">
            <span>Items Sold:</span>
            <span><?= number_format($items_result['total_items']) ?></span>
        </div>
        
        <?php if ($total_transactions > 0): ?>
        <div class="row">
            <span>Avg Transaction:</span>
            <span>Rs <?= number_format($total_sales_amount / $total_transactions, 2) ?></span>
        </div>
        <?php endif; ?>
        
        <div class="line"></div>
        
        <!-- Cash Till -->
        <div class="center bold small">CASH TILL</div>
        
        <div class="row">
            <span>Opening Cash:</span>
            <span>Rs <?= number_format($opening_cash, 2) ?></span>
        </div>
        
        <div class="row">
            <span>Cash Received:</span>
            <span>Rs <?= number_format($cash_received, 2) ?></span>
        </div>
        
        <?php if ($expenses_result['cash_expenses'] > 0): ?>
        <div class="row">
            <span>Cash Expenses:</span>
            <span>-Rs <?= number_format($expenses_result['cash_expenses'], 2) ?></span>
        </div>
        <?php endif; ?>
        
        <div class="total-row">
            <span>Expected in Till:</span>
            <span>Rs <?= number_format($cash_received - $change_given - $expenses_result['cash_expenses'], 2) ?></span>
        </div>
        
        <div class="row">
            <span>Actual Count:</span>
            <span>Rs _______</span>
        </div>
        
        <div class="row">
            <span>Difference:</span>
            <span>Rs _______</span>
        </div>
        
        <div class="line"></div>
        
        <!-- Expenses Summary -->
        <?php if ($expenses_result['total_expenses'] > 0): ?>
        <div class="center bold small">EXPENSES DETAILS</div>
        
        <div class="row">
            <span>Total Expenses:</span>
            <span>Rs <?= number_format($expenses_result['total_expenses'], 2) ?></span>
        </div>
        
        <div class="line"></div>
        
        <?php if (count($expenses_detail) > 0): ?>
            <?php foreach ($expenses_detail as $index => $expense): ?>
            <div class="small" style="margin: 5px 0;">
                <div style="font-weight: bold;">
                    <?= ($index + 1) ?>. <?= ucfirst($expense['category']) ?> - Rs <?= number_format($expense['amount'], 2) ?>
                </div>
                <div style="margin-left: 10px; font-size: 12px;">
                    Time: <?= $expense['expense_time'] ?> | Date: <?= $expense['expense_date_formatted'] ?>
                </div>
                <div style="margin-left: 10px; font-size: 12px;">
                    Payment: <?= ucfirst($expense['payment_method']) ?>
                </div>
                <?php if (!empty($expense['description'])): ?>
                <div style="margin-left: 10px; font-size: 12px;">
                    Reason: <?= htmlspecialchars($expense['description']) ?>
                </div>
                <?php endif; ?>
            </div>
            <?php if ($index < count($expenses_detail) - 1): ?>
            <div style="border-bottom: 1px dotted #000; margin: 3px 0;"></div>
            <?php endif; ?>
            <?php endforeach; ?>
        <?php endif; ?>
        
        <div class="line"></div>
        <?php else: ?>
        <div class="line"></div>
        <?php endif; ?>
        
        <div class="solid-line"></div>
        
        <!-- Signature Lines -->
        <div class="small">
            <div>Staff: ________________</div>
            <div style="margin-top: 8px;">Manager: ________________</div>
        </div>
        
        <div class="line"></div>
        
        <!-- Footer -->
        <div class="center small">
            <div>End of Day Report</div>
            <div><?= date('H:i:s') ?></div>
        </div>
        
        <!-- Developer Credit -->
        <div class="center" style="border-top: 1px dotted #000; margin-top: 10px; padding-top: 5px; font-size: 11px; color: #666;">
            <div>System developed by</div>
            <div>Ecodez Digital solution</div>
            <div>0751534972</div>
        </div>
    </div>
    
    <div class="no-print" style="text-align: center; margin-top: 10px;">
        <button onclick="window.print()">Print Summary</button>
        <button onclick="closeWindow()">Close</button>
        <br><br>
        <a href="daily_summary.php?date=<?= $selected_date ?>" style="font-size: 10px;">View Full Report</a>
    </div>
    
    <script>
        function closeWindow() {
            // Try to close the window (works for popups)
            if (window.opener || window.parent !== window) {
                window.close();
            } else {
                // If it's a regular tab, go back or to reports page
                if (history.length > 1) {
                    history.back();
                } else {
                    window.location.href = '../reports/';
                }
            }
        }
        
        window.onload = function() {
            window.print();
        };
    </script>
</body>
</html>
