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

$shop_id = $_SESSION['user']['shop_id'] ?? 0;

if ($shop_id == 0) {
    die("Shop session missing.");
}

// Get filter parameters from URL
$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'] ?? '';

// Get shop details
$shop_sql = "SELECT * FROM shops WHERE id = :shop_id";
$shop_stmt = $pdo->prepare($shop_sql);
$shop_stmt->execute([':shop_id' => $shop_id]);
$shop = $shop_stmt->fetch(PDO::FETCH_ASSOC);

// Build WHERE clause
$where_clauses = ["s.shop_id = :shop_id", "DATE(s.sale_date) BETWEEN :from_date AND :to_date"];
$params = [
    ':shop_id' => $shop_id,
    ':from_date' => $from_date,
    ':to_date' => $to_date
];

if (!empty($status)) {
    $where_clauses[] = "s.status = :status";
    $params[':status'] = $status;
}

if (!empty($payment_method)) {
    $where_clauses[] = "p.method = :payment_method";
    $params[':payment_method'] = $payment_method;
}

$where_sql = !empty($where_clauses) ? "WHERE " . implode(" AND ", $where_clauses) : "";

// Get sales summary
$summary_sql = "SELECT 
                  COUNT(DISTINCT s.id) as total_sales,
                  SUM(s.total) as total_revenue,
                  SUM(s.paid) as total_paid,
                  AVG(s.total) as avg_sale,
                  COUNT(DISTINCT s.customer_id) as total_customers,
                  SUM(CASE WHEN s.status = 'paid' THEN 1 ELSE 0 END) as paid_count,
                  SUM(CASE WHEN s.status = 'open' THEN 1 ELSE 0 END) as open_count,
                  SUM(CASE WHEN s.status = 'partially_paid' THEN 1 ELSE 0 END) as partial_count,
                  SUM(CASE WHEN s.status = 'cancelled' THEN 1 ELSE 0 END) as cancelled_count
                FROM sales s
                LEFT JOIN payments p ON s.id = p.sale_id
                $where_sql";

$summary_stmt = $pdo->prepare($summary_sql);
$summary_stmt->execute($params);
$summary = $summary_stmt->fetch(PDO::FETCH_ASSOC);

// Get sales data
$sales_sql = "SELECT 
                s.*,
                COALESCE(c.name, 'Walk-in Customer') as customer_name,
                c.phone as customer_phone,
                GROUP_CONCAT(DISTINCT p.method) as payment_methods,
                COUNT(DISTINCT sl.id) as item_count,
                SUM(sl.qty) as total_qty,
                (s.total - s.paid) as due_amount
              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 payments p ON s.id = p.sale_id
              $where_sql
              GROUP BY s.id
              ORDER BY s.sale_date DESC";

$sales_stmt = $pdo->prepare($sales_sql);
$sales_stmt->execute($params);
$sales = $sales_stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sales Report - <?= date('Y-m-d') ?></title>
    <style>
        @media print {
            body * {
                visibility: hidden;
            }
            .report-container, .report-container * {
                visibility: visible;
            }
            .report-container {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
            }
            .no-print {
                display: none !important;
            }
            .page-break {
                page-break-after: always;
            }
        }
        
        body {
            font-family: Arial, sans-serif;
            font-size: 12px;
            line-height: 1.4;
            background: #fff;
            color: #000;
            margin: 0;
            padding: 15px;
        }
        
        .report-container {
            max-width: 1000px;
            margin: 0 auto;
        }
        
        .report-header {
            text-align: center;
            margin-bottom: 20px;
            border-bottom: 2px solid #000;
            padding-bottom: 15px;
        }
        
        .shop-name {
            font-size: 24px;
            font-weight: bold;
            margin: 0;
            color: #2c3e50;
        }
        
        .report-title {
            font-size: 18px;
            font-weight: bold;
            margin: 10px 0;
            color: #27ae60;
        }
        
        .report-period {
            font-size: 14px;
            margin: 5px 0;
        }
        
        .summary-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin: 20px 0;
        }
        
        .summary-card {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            text-align: center;
            background: #f8f9fa;
        }
        
        .summary-card .value {
            font-size: 24px;
            font-weight: bold;
            margin: 5px 0;
        }
        
        .summary-card .label {
            font-size: 12px;
            color: #666;
        }
        
        .status-summary {
            display: flex;
            justify-content: space-around;
            margin: 20px 0;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
        }
        
        .status-item {
            text-align: center;
        }
        
        .status-item .count {
            font-size: 20px;
            font-weight: bold;
            margin: 5px 0;
        }
        
        .status-paid .count { color: #28a745; }
        .status-open .count { color: #ffc107; }
        .status-partial .count { color: #17a2b8; }
        .status-cancelled .count { color: #dc3545; }
        
        .sales-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        
        .sales-table th {
            background: #2c3e50;
            color: white;
            padding: 8px;
            text-align: left;
            border: 1px solid #ddd;
        }
        
        .sales-table td {
            padding: 6px;
            border: 1px solid #ddd;
        }
        
        .sales-table tr:nth-child(even) {
            background: #f8f9fa;
        }
        
        .sales-table .status {
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 10px;
            font-weight: bold;
        }
        
        .status-paid { background: #d4edda; color: #155724; }
        .status-open { background: #fff3cd; color: #856404; }
        .status-partially_paid { background: #d1ecf1; color: #0c5460; }
        .status-cancelled { background: #f8d7da; color: #721c24; }
        
        .text-right {
            text-align: right;
        }
        
        .text-center {
            text-align: center;
        }
        
        .footer {
            margin-top: 30px;
            padding-top: 15px;
            border-top: 1px solid #ddd;
            text-align: center;
            color: #666;
            font-size: 11px;
        }
        
        .print-button {
            text-align: center;
            margin: 20px 0;
        }
        
        .filter-info {
            background: #f1f8ff;
            padding: 10px;
            border-radius: 5px;
            margin: 15px 0;
            font-size: 11px;
        }
    </style>
</head>
<body>
    <div class="report-container">
        <!-- Header -->
        <div class="report-header">
            <h1 class="shop-name"><?= htmlspecialchars($shop['name'] ?? 'Pharmacy') ?></h1>
            <div class="report-title">SALES REPORT</div>
            <div class="report-period">
                Period: <?= date('d/m/Y', strtotime($from_date)) ?> - <?= date('d/m/Y', strtotime($to_date)) ?>
            </div>
            <div class="report-period">
                Generated on: <?= date('d/m/Y H:i:s') ?>
            </div>
        </div>
        
        <!-- Filter Info -->
        <div class="filter-info">
            <strong>Filters Applied:</strong>
            <?php if ($status): ?> | Status: <?= ucfirst($status) ?> <?php endif; ?>
            <?php if ($payment_method): ?> | Payment Method: <?= $payment_method ?> <?php endif; ?>
        </div>
        
        <!-- Summary Cards -->
        <div class="summary-cards">
            <div class="summary-card">
                <div class="value"><?= number_format($summary['total_sales'] ?? 0) ?></div>
                <div class="label">Total Sales</div>
            </div>
            <div class="summary-card">
                <div class="value">TZS <?= number_format($summary['total_revenue'] ?? 0, 2) ?></div>
                <div class="label">Total Revenue</div>
            </div>
            <div class="summary-card">
                <div class="value">TZS <?= number_format($summary['total_paid'] ?? 0, 2) ?></div>
                <div class="label">Amount Collected</div>
            </div>
            <div class="summary-card">
                <div class="value"><?= number_format($summary['total_customers'] ?? 0) ?></div>
                <div class="label">Customers</div>
            </div>
        </div>
        
        <!-- Status Summary -->
        <div class="status-summary">
            <div class="status-item status-paid">
                <div class="label">Paid</div>
                <div class="count"><?= number_format($summary['paid_count'] ?? 0) ?></div>
            </div>
            <div class="status-item status-open">
                <div class="label">Open</div>
                <div class="count"><?= number_format($summary['open_count'] ?? 0) ?></div>
            </div>
            <div class="status-item status-partial">
                <div class="label">Partial</div>
                <div class="count"><?= number_format($summary['partial_count'] ?? 0) ?></div>
            </div>
            <div class="status-item status-cancelled">
                <div class="label">Cancelled</div>
                <div class="count"><?= number_format($summary['cancelled_count'] ?? 0) ?></div>
            </div>
        </div>
        
        <!-- Sales Table -->
        <h3>Sales Details</h3>
        <table class="sales-table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Invoice No</th>
                    <th>Date</th>
                    <th>Customer</th>
                    <th>Items</th>
                    <th class="text-right">Total</th>
                    <th class="text-right">Paid</th>
                    <th class="text-right">Due</th>
                    <th>Payment</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($sales as $index => $sale): ?>
                <tr>
                    <td class="text-center"><?= $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']) ?></td>
                    <td class="text-center"><?= $sale['item_count'] ?></td>
                    <td class="text-right">TZS <?= number_format($sale['total'], 2) ?></td>
                    <td class="text-right">TZS <?= number_format($sale['paid'], 2) ?></td>
                    <td class="text-right">TZS <?= number_format($sale['due_amount'], 2) ?></td>
                    <td><?= htmlspecialchars($sale['payment_methods'] ?? '') ?></td>
                    <td>
                        <span class="status status-<?= $sale['status'] ?>">
                            <?= ucfirst(str_replace('_', ' ', $sale['status'])) ?>
                        </span>
                    </td>
                </tr>
                <?php endforeach; ?>
                
                <?php if (empty($sales)): ?>
                <tr>
                    <td colspan="10" class="text-center">No sales found for the selected period</td>
                </tr>
                <?php endif; ?>
            </tbody>
            <tfoot>
                <tr style="background: #e9ecef;">
                    <td colspan="5" class="text-right"><strong>TOTALS:</strong></td>
                    <td class="text-right"><strong>TZS <?= number_format($summary['total_revenue'] ?? 0, 2) ?></strong></td>
                    <td class="text-right"><strong>TZS <?= number_format($summary['total_paid'] ?? 0, 2) ?></strong></td>
                    <td class="text-right"><strong>TZS <?= number_format(($summary['total_revenue'] ?? 0) - ($summary['total_paid'] ?? 0), 2) ?></strong></td>
                    <td colspan="2"></td>
                </tr>
            </tfoot>
        </table>
        
        <!-- Footer -->
        <div class="footer">
            <div>This is a computer generated report</div>
            <div><?= htmlspecialchars($shop['name'] ?? 'Pharmacy') ?> | <?= htmlspecialchars($shop['address'] ?? '') ?></div>
            <div>Page 1 of 1</div>
        </div>
    </div>
    
    <!-- Print Button -->
    <div class="print-button no-print">
        <button onclick="window.print()" class="btn btn-primary">
            <i class="fas fa-print"></i> Print Report
        </button>
        <button onclick="window.close()" class="btn btn-secondary">
            <i class="fas fa-times"></i> Close
        </button>
    </div>
    
    <script>
        // Auto-print after 1 second
        setTimeout(function() {
            window.print();
        }, 1000);
        
        // Close window after print
        window.onafterprint = function() {
            setTimeout(function() {
                window.close();
            }, 500);
        };
    </script>
</body>
</html>