<?php
// modules/sales/print_sales_report.php
session_start();
require_once '../assets/db_connect.php';

// Check if user is logged in
if (!isset($_SESSION['user'])) {
    die("Access denied. Please login.");
}

$shop_id = $_SESSION['user']['shop_id'] ?? 0;
$user_role = $_SESSION['user']['role'] ?? 'cashier';
$user_name = $_SESSION['user']['fullname'] ?? 'User';

// Get filter parameters
$from_date = $_GET['from_date'] ?? date('Y-m-d', strtotime('-30 days'));
$to_date = $_GET['to_date'] ?? date('Y-m-d');
$status = $_GET['status'] ?? '';
$payment_method = $_GET['payment_method'] ?? '';
$search = $_GET['search'] ?? '';

// Build query
$sql = "SELECT 
            s.id,
            s.invoice_no,
            s.sale_date,
            c.name as customer_name,
            c.phone as customer_phone,
            COUNT(DISTINCT sl.id) as items_count,
            SUM(sl.qty) as total_quantity,
            s.total,
            s.paid,
            s.total - s.paid as due,
            s.status,
            u.fullname as cashier_name,
            GROUP_CONCAT(DISTINCT p.name SEPARATOR ', ') as products_sold
        FROM sales s
        LEFT JOIN customers c ON s.customer_id = c.id
        LEFT JOIN sale_lines sl ON s.id = sl.sale_id
        LEFT JOIN products p ON sl.product_id = p.id
        LEFT JOIN users u ON s.created_by = u.id
        WHERE s.shop_id = ?
        AND DATE(s.sale_date) BETWEEN ? AND ?";

$params = [$shop_id, $from_date, $to_date];

// Add filters
if (!empty($status)) {
    $sql .= " AND s.status = ?";
    $params[] = $status;
}

if (!empty($search)) {
    $sql .= " AND (s.invoice_no LIKE ? OR c.name LIKE ? OR c.phone LIKE ?)";
    $searchTerm = "%$search%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

$sql .= " GROUP BY s.id, s.invoice_no, s.sale_date, c.name, c.phone, s.total, s.paid, s.status, u.fullname
          ORDER BY s.sale_date DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$sales = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get shop info
$shop_sql = "SELECT name, address, phone FROM shops WHERE id = ?";
$shop_stmt = $pdo->prepare($shop_sql);
$shop_stmt->execute([$shop_id]);
$shop = $shop_stmt->fetch(PDO::FETCH_ASSOC);

// Calculate totals
$total_sales = 0;
$total_paid = 0;
$total_due = 0;
$total_items = 0;
$total_quantity = 0;

foreach ($sales as $sale) {
    $total_sales += $sale['total'];
    $total_paid += $sale['paid'];
    $total_due += $sale['due'];
    $total_items += $sale['items_count'];
    $total_quantity += $sale['total_quantity'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sales Report - <?= $shop['name'] ?></title>
    <style>
        @media print {
            @page {
                size: A4 portrait;
                margin: 15mm;
            }
            
            body {
                font-family: 'Arial', sans-serif;
                font-size: 12px;
                line-height: 1.4;
                color: #000;
            }
            
            .no-print {
                display: none !important;
            }
            
            .print-header {
                display: block !important;
            }
            
            .page-break {
                page-break-after: always;
            }
            
            table {
                page-break-inside: auto;
            }
            
            tr {
                page-break-inside: avoid;
                page-break-after: auto;
            }
        }
        
        body {
            font-family: 'Arial', sans-serif;
            font-size: 12px;
            line-height: 1.4;
            color: #333;
            margin: 0;
            padding: 20px;
            background: #fff;
        }
        
        .print-header {
            text-align: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #333;
            display: none;
        }
        
        .shop-info {
            margin-bottom: 20px;
        }
        
        .shop-name {
            font-size: 24px;
            font-weight: bold;
            color: #2c3e50;
            margin-bottom: 5px;
        }
        
        .shop-address {
            font-size: 14px;
            color: #7f8c8d;
            margin-bottom: 5px;
        }
        
        .report-title {
            font-size: 18px;
            font-weight: bold;
            text-align: center;
            margin: 20px 0;
            color: #2c3e50;
        }
        
        .report-info {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 5px;
        }
        
        .report-info div {
            flex: 1;
        }
        
        .date-range {
            text-align: center;
            font-weight: bold;
            margin-bottom: 10px;
            color: #e74c3c;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        
        th {
            background-color: #2c3e50;
            color: white;
            font-weight: bold;
            padding: 8px;
            text-align: left;
            border: 1px solid #ddd;
        }
        
        td {
            padding: 8px;
            border: 1px solid #ddd;
            vertical-align: top;
        }
        
        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        
        tr:hover {
            background-color: #f5f5f5;
        }
        
        .amount {
            text-align: right;
            font-family: 'Courier New', monospace;
        }
        
        .status-paid {
            color: #27ae60;
            font-weight: bold;
        }
        
        .status-open {
            color: #f39c12;
            font-weight: bold;
        }
        
        .status-partially_paid {
            color: #3498db;
            font-weight: bold;
        }
        
        .status-cancelled {
            color: #e74c3c;
            font-weight: bold;
        }
        
        .summary-box {
            border: 2px solid #2c3e50;
            border-radius: 5px;
            padding: 15px;
            margin: 20px 0;
            background: #f8f9fa;
        }
        
        .summary-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 15px;
            color: #2c3e50;
            text-align: center;
        }
        
        .summary-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
        }
        
        .summary-item {
            text-align: center;
            padding: 10px;
            background: white;
            border-radius: 5px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .summary-label {
            font-size: 12px;
            color: #7f8c8d;
            margin-bottom: 5px;
        }
        
        .summary-value {
            font-size: 18px;
            font-weight: bold;
            color: #2c3e50;
        }
        
        .summary-value.total {
            color: #27ae60;
        }
        
        .summary-value.paid {
            color: #3498db;
        }
        
        .summary-value.due {
            color: #e74c3c;
        }
        
        .footer {
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #ddd;
            text-align: center;
            color: #7f8c8d;
            font-size: 11px;
        }
        
        .print-controls {
            position: fixed;
            top: 20px;
            right: 20px;
            background: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            z-index: 1000;
        }
        
        .print-btn {
            background: #27ae60;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            margin: 5px;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .print-btn:hover {
            background: #219653;
        }
        
        .print-btn.close {
            background: #e74c3c;
        }
        
        .print-btn.close:hover {
            background: #c0392b;
        }
        
        .page-info {
            text-align: right;
            font-size: 11px;
            color: #7f8c8d;
            margin-top: 5px;
        }
        
        .timestamp {
            color: #7f8c8d;
            font-size: 11px;
            text-align: center;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <!-- Print Controls (hidden when printing) -->
    <div class="print-controls no-print">
        <button onclick="window.print()" class="print-btn">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
                <path d="M13 0H3a2 2 0 0 0-2 2v4h2V2h10v4h2V2a2 2 0 0 0-2-2z"/>
                <path d="M13 9H3a1 1 0 0 0-1 1v3h1v-2h10v2h1v-3a1 1 0 0 0-1-1z"/>
                <path d="M2 12h1v2H2z"/>
                <path d="M4 12h1v2H4z"/>
                <path d="M11 12h1v2h-1z"/>
                <path d="M13 12h1v2h-1z"/>
            </svg>
            Print Report
        </button>
        <button onclick="window.close()" class="print-btn close">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
                <path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z"/>
            </svg>
            Close
        </button>
    </div>

    <!-- Print Header -->
    <div class="print-header">
        <div class="shop-name"><?= htmlspecialchars($shop['name']) ?></div>
        <div class="shop-address"><?= htmlspecialchars($shop['address']) ?></div>
        <div class="shop-address">Tel: <?= htmlspecialchars($shop['phone']) ?></div>
    </div>

    <!-- Report Content -->
    <div class="shop-info">
        <div class="shop-name"><?= htmlspecialchars($shop['name']) ?></div>
        <div class="shop-address"><?= htmlspecialchars($shop['address']) ?></div>
        <div class="shop-address">Tel: <?= htmlspecialchars($shop['phone']) ?></div>
    </div>
    
    <div class="report-title">SALES REPORT</div>
    
    <div class="date-range">
        From: <?= date('d/m/Y', strtotime($from_date)) ?> 
        To: <?= date('d/m/Y', strtotime($to_date)) ?>
    </div>
    
    <div class="timestamp">
        Generated on: <?= date('d/m/Y H:i:s') ?> 
        by <?= htmlspecialchars($user_name) ?>
    </div>
    
    <div class="report-info">
        <div>
            <strong>Report Period:</strong><br>
            <?= date('F d, Y', strtotime($from_date)) ?> - <?= date('F d, Y', strtotime($to_date)) ?>
        </div>
        <div>
            <strong>Generated By:</strong><br>
            <?= htmlspecialchars($user_name) ?><br>
            Role: <?= htmlspecialchars($user_role) ?>
        </div>
        <div>
            <strong>Filters Applied:</strong><br>
            Status: <?= $status ? ucfirst(str_replace('_', ' ', $status)) : 'All' ?><br>
            Payment: <?= $payment_method ?: 'All Methods' ?>
        </div>
    </div>
    
    <!-- Sales Table -->
    <table>
        <thead>
            <tr>
                <th width="50">#</th>
                <th width="120">Invoice No</th>
                <th width="150">Date & Time</th>
                <th width="150">Customer</th>
                <th width="80">Items</th>
                <th width="80">Qty</th>
                <th width="100">Total (TZS)</th>
                <th width="100">Paid (TZS)</th>
                <th width="100">Due (TZS)</th>
                <th width="90">Status</th>
                <th>Products</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($sales)): ?>
                <tr>
                    <td colspan="11" style="text-align: center; padding: 20px; color: #7f8c8d;">
                        No sales found for the selected period
                    </td>
                </tr>
            <?php else: ?>
                <?php foreach ($sales as $index => $sale): ?>
                    <tr>
                        <td><?= $index + 1 ?></td>
                        <td><?= htmlspecialchars($sale['invoice_no']) ?></td>
                        <td><?= date('d/m/Y H:i', strtotime($sale['sale_date'])) ?></td>
                        <td>
                            <?= htmlspecialchars($sale['customer_name'] ?: 'Walk-in Customer') ?>
                            <?php if ($sale['customer_phone']): ?>
                                <br><small><?= htmlspecialchars($sale['customer_phone']) ?></small>
                            <?php endif; ?>
                        </td>
                        <td style="text-align: center;"><?= $sale['items_count'] ?></td>
                        <td style="text-align: center;"><?= $sale['total_quantity'] ?></td>
                        <td class="amount"><?= number_format($sale['total'], 2) ?></td>
                        <td class="amount"><?= number_format($sale['paid'], 2) ?></td>
                        <td class="amount"><?= number_format($sale['due'], 2) ?></td>
                        <td class="status-<?= $sale['status'] ?>">
                            <?= ucfirst(str_replace('_', ' ', $sale['status'])) ?>
                        </td>
                        <td>
                            <small><?= htmlspecialchars($sale['products_sold'] ?: 'N/A') ?></small>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
        <tfoot>
            <tr style="background-color: #f1f8e9; font-weight: bold;">
                <td colspan="5" style="text-align: right; padding-right: 20px;">TOTALS:</td>
                <td style="text-align: center;"><?= number_format($total_quantity) ?></td>
                <td class="amount" style="color: #27ae60;"><?= number_format($total_sales, 2) ?></td>
                <td class="amount" style="color: #3498db;"><?= number_format($total_paid, 2) ?></td>
                <td class="amount" style="color: #e74c3c;"><?= number_format($total_due, 2) ?></td>
                <td colspan="2"></td>
            </tr>
        </tfoot>
    </table>
    
    <!-- Summary Section -->
    <div class="summary-box">
        <div class="summary-title">REPORT SUMMARY</div>
        <div class="summary-grid">
            <div class="summary-item">
                <div class="summary-label">Total Transactions</div>
                <div class="summary-value"><?= count($sales) ?></div>
            </div>
            <div class="summary-item">
                <div class="summary-label">Total Items Sold</div>
                <div class="summary-value"><?= number_format($total_items) ?></div>
            </div>
            <div class="summary-item">
                <div class="summary-label">Total Quantity</div>
                <div class="summary-value"><?= number_format($total_quantity) ?></div>
            </div>
            <div class="summary-item">
                <div class="summary-label">Total Revenue</div>
                <div class="summary-value total">TZS <?= number_format($total_sales, 2) ?></div>
            </div>
            <div class="summary-item">
                <div class="summary-label">Total Collected</div>
                <div class="summary-value paid">TZS <?= number_format($total_paid, 2) ?></div>
            </div>
            <div class="summary-item">
                <div class="summary-label">Total Due</div>
                <div class="summary-value due">TZS <?= number_format($total_due, 2) ?></div>
            </div>
        </div>
    </div>
    
    <!-- Status Summary -->
    <div style="margin: 20px 0; display: flex; gap: 15px; flex-wrap: wrap;">
        <?php
        $status_counts = [];
        foreach ($sales as $sale) {
            $status_counts[$sale['status']] = ($status_counts[$sale['status']] ?? 0) + 1;
        }
        ?>
        <?php foreach ($status_counts as $status_type => $count): ?>
            <div style="padding: 8px 15px; background: #f8f9fa; border-radius: 5px;">
                <strong><?= ucfirst(str_replace('_', ' ', $status_type)) ?>:</strong> 
                <span class="status-<?= $status_type ?>"><?= $count ?></span>
            </div>
        <?php endforeach; ?>
    </div>
    
    <!-- Footer -->
    <div class="footer">
        <div>--- End of Report ---</div>
        <div><?= $shop['name'] ?> - Sales Management System</div>
        <div>Report generated automatically on <?= date('d/m/Y H:i:s') ?></div>
        <div>Page 1 of 1</div>
    </div>
    
    <script>
        // Auto-print if print parameter is set
        if (window.location.search.includes('auto_print=1')) {
            window.print();
        }
        
        // Add page numbers for multi-page reports
        document.addEventListener('DOMContentLoaded', function() {
            const tables = document.querySelectorAll('table');
            tables.forEach((table, index) => {
                const pageNumber = index + 1;
                const pageInfo = document.createElement('div');
                pageInfo.className = 'page-info';
                pageInfo.textContent = `Page ${pageNumber}`;
                table.parentNode.insertBefore(pageInfo, table.nextSibling);
            });
        });
    </script>
</body>
</html>