<?php
session_start();
include 'db.php';

$shift_id = $_GET['shift_id'] ?? null;
$closing_cash = $_GET['closing_cash'] ?? 0;

if (!$shift_id) {
    die('Shift ID required');
}

// Get shift data
$stmt = $conn->prepare("
    SELECT s.*, u.username, u.email, st.store_name
    FROM shifts s
    LEFT JOIN users u ON s.user_id = u.id
    LEFT JOIN stores st ON s.store_id = st.id
    WHERE s.id = ?
");
$stmt->bind_param("i", $shift_id);
$stmt->execute();
$shift = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$shift) {
    die('Shift not found');
}

// Get sales summary by payment method
$sales_stmt = $conn->prepare("
    SELECT 
        payment_method,
        COUNT(*) as transaction_count,
        SUM(total_amount) as total_amount,
        SUM(tax_amount) as total_tax,
        SUM(discount_amount) as total_discount,
        SUM(net_amount) as net_amount
    FROM sales 
    WHERE shift_id = ?
    GROUP BY payment_method
");
$sales_stmt->bind_param("i", $shift_id);
$sales_stmt->execute();
$sales_result = $sales_stmt->get_result();
$sales_summary = [];
$total_sales = 0;
$total_tax = 0;
$total_discount = 0;
$total_net = 0;

while ($row = $sales_result->fetch_assoc()) {
    $sales_summary[] = $row;
    $total_sales += floatval($row['total_amount']);
    $total_tax += floatval($row['total_tax']);
    $total_discount += floatval($row['total_discount']);
    $total_net += floatval($row['net_amount']);
}
$sales_stmt->close();

// Get shift logs
$log_stmt = $conn->prepare("
    SELECT 
        action_type,
        SUM(amount) as total_amount,
        COUNT(*) as transaction_count
    FROM shift_logs 
    WHERE shift_id = ?
    GROUP BY action_type
");
$log_stmt->bind_param("i", $shift_id);
$log_stmt->execute();
$log_result = $log_stmt->get_result();
$shift_logs = [];
$cash_in = 0;
$cash_out = 0;

while ($row = $log_result->fetch_assoc()) {
    $shift_logs[] = $row;
    if ($row['action_type'] === 'cash_in') {
        $cash_in = floatval($row['total_amount']);
    } elseif ($row['action_type'] === 'cash_out') {
        $cash_out = floatval($row['total_amount']);
    }
}
$log_stmt->close();

// Get cash sales from sales summary
$cash_sales = 0;
foreach ($sales_summary as $sale) {
    if ($sale['payment_method'] === 'cash') {
        $cash_sales = floatval($sale['total_amount']);
        break;
    }
}

// Calculate expected cash
$expected_cash = floatval($shift['opening_cash']) + $cash_sales + $cash_in - $cash_out;
$discrepancy = floatval($closing_cash) - $expected_cash;

// Get receipt font size setting
$receipt_font_size = 12; // Default for thermal printer
$result = $conn->query("SELECT value FROM settings WHERE code = 'receipt_font_size' AND is_active = 1 LIMIT 1");
if ($result && $row = $result->fetch_assoc()) {
    $receipt_font_size = intval($row['value']);
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Shift Summary</title>
    <style>
        body {
            font-family: 'Courier New', monospace;
            font-size: <?= $receipt_font_size ?>px;
            margin: 0;
            padding: 0;
            background: #fff;
            width: 80mm;
        }
        
        .receipt-wrapper {
            width: 100%;
            padding: 5px;
            box-sizing: border-box;
        }
        
        .header {
            text-align: center;
            font-weight: bold;
            margin-bottom: 10px;
            border-bottom: 1px dashed #000;
            padding-bottom: 5px;
        }
        
        .section {
            margin-bottom: 10px;
        }
        
        .section-title {
            font-weight: bold;
            text-align: center;
            margin-bottom: 5px;
            border-bottom: 1px solid #000;
        }
        
        .row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 2px;
        }
        
        .label {
            font-weight: bold;
        }
        
        .value {
            text-align: right;
        }
        
        .total-row {
            border-top: 1px solid #000;
            padding-top: 5px;
            margin-top: 5px;
            font-weight: bold;
        }
        
        .discrepancy {
            border-top: 2px solid #000;
            padding-top: 5px;
            margin-top: 10px;
            font-weight: bold;
        }
        
        .discrepancy.positive {
            color: green;
        }
        
        .discrepancy.negative {
            color: red;
        }
        
        .footer {
            text-align: center;
            margin-top: 15px;
            border-top: 1px dashed #000;
            padding-top: 5px;
            font-size: <?= $receipt_font_size - 2 ?>px;
        }
        
        @media print {
            body {
                width: 80mm;
                margin: 0;
                padding: 0;
            }
        }
    </style>
</head>
<body>
    <div class="receipt-wrapper">
                 <div class="header">
             <div><?= htmlspecialchars($shift['store_name'] ?? 'ITRPOS STORE') ?></div>
            <div>SHIFT SUMMARY</div>
            <div><?= date('d/m/Y H:i', strtotime($shift['end_time'] ?? 'now')) ?></div>
        </div>

        <div class="section">
            <div class="section-title">SHIFT DETAILS</div>
            <div class="row">
                <span class="label">Shift ID:</span>
                <span class="value"><?= $shift['id'] ?></span>
            </div>
            <div class="row">
                <span class="label">Cashier:</span>
                <span class="value"><?= htmlspecialchars($shift['username']) ?></span>
            </div>
            <div class="row">
                <span class="label">Start Time:</span>
                <span class="value"><?= date('H:i', strtotime($shift['start_time'])) ?></span>
            </div>
            <div class="row">
                <span class="label">End Time:</span>
                <span class="value"><?= date('H:i', strtotime($shift['end_time'] ?? 'now')) ?></span>
            </div>
        </div>

        <div class="section">
            <div class="section-title">SALES SUMMARY</div>
            <?php foreach ($sales_summary as $sale): ?>
            <div class="row">
                <span class="label"><?= strtoupper($sale['payment_method']) ?>:</span>
                <span class="value"><?= number_format($sale['total_amount'], 2) ?></span>
            </div>
            <div class="row" style="font-size: <?= $receipt_font_size - 2 ?>px; margin-left: 10px;">
                <span>Transactions: <?= $sale['transaction_count'] ?></span>
                <span>Net: <?= number_format($sale['net_amount'], 2) ?></span>
            </div>
            <?php endforeach; ?>
            
            <div class="row total-row">
                <span class="label">TOTAL SALES:</span>
                <span class="value"><?= number_format($total_sales, 2) ?></span>
            </div>
            <div class="row">
                <span class="label">Total Tax:</span>
                <span class="value"><?= number_format($total_tax, 2) ?></span>
            </div>
            <div class="row">
                <span class="label">Total Discount:</span>
                <span class="value"><?= number_format($total_discount, 2) ?></span>
            </div>
            <div class="row total-row">
                <span class="label">NET SALES:</span>
                <span class="value"><?= number_format($total_net, 2) ?></span>
            </div>
        </div>

        <div class="section">
            <div class="section-title">CASH MOVEMENTS</div>
            <div class="row">
                <span class="label">Opening Cash:</span>
                <span class="value"><?= number_format($shift['opening_cash'], 2) ?></span>
            </div>
            <div class="row">
                <span class="label">Cash Sales:</span>
                <span class="value"><?= number_format($cash_sales, 2) ?></span>
            </div>
            <?php if ($cash_in > 0): ?>
            <div class="row">
                <span class="label">Cash In:</span>
                <span class="value"><?= number_format($cash_in, 2) ?></span>
            </div>
            <?php endif; ?>
            <?php if ($cash_out > 0): ?>
            <div class="row">
                <span class="label">Cash Out:</span>
                <span class="value">-<?= number_format($cash_out, 2) ?></span>
            </div>
            <?php endif; ?>
            <div class="row total-row">
                <span class="label">EXPECTED CASH:</span>
                <span class="value"><?= number_format($expected_cash, 2) ?></span>
            </div>
            <div class="row">
                <span class="label">Actual Cash:</span>
                <span class="value"><?= number_format($closing_cash, 2) ?></span>
            </div>
                         <div class="row discrepancy <?= $discrepancy >= 0 ? 'positive' : 'negative' ?>">
                 <span class="label">DISCREPANCY:</span>
                 <span class="value"><?= ($discrepancy >= 0 ? '+' : '-') . number_format(abs($discrepancy), 2) ?></span>
             </div>
        </div>

        <div class="footer">
            <div>Shift Summary - <?= date('d/m/Y H:i:s') ?></div>
            <div>Generated by ITRPOS</div>
        </div>
    </div>

    <script>
        window.onload = function() {
            window.print();
        };
    </script>
</body>
</html>
