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

// Handle CSV export BEFORE any output
if (isset($_GET['export']) && $_GET['export']==='csv') {
    // Get parameters
    $start_date = $_GET['start_date'] ?? date('Y-m-d');
    $end_date = $_GET['end_date'] ?? date('Y-m-d');
    $shop_id = $_GET['shop_id'] ?? 0;
    $user_role = $_SESSION['user']['role'] ?? '';
    $user_shop_id = $_SESSION['user']['shop_id'] ?? 0;
    
    // Fetch data for CSV
    $sql = "
    SELECT 
        DATE(s.sale_date) as sale_day,
        COUNT(DISTINCT s.id) as invoice_count,
        COUNT(DISTINCT s.customer_id) as customer_count,
        SUM(sl.qty) as total_quantity,
        SUM(sl.qty * sl.unit_price) as gross_amount,
        SUM(sl.discount) as total_discount,
        SUM(sl.line_total) as net_amount,
        SUM(COALESCE(p.amount, 0)) as total_paid,
        AVG(sl.unit_price) as avg_price,
        GREATEST(SUM(s.total - COALESCE(p.amount, 0)), 0) as outstanding_amount,
        s.shop_id,
        sh.name as shop_name
    FROM sales s
    LEFT JOIN sale_lines sl ON s.id = sl.sale_id
    LEFT JOIN (
        SELECT sale_id, SUM(amount) as amount 
        FROM payments 
        GROUP BY sale_id
    ) p ON s.id = p.sale_id
    LEFT JOIN shops sh ON s.shop_id = sh.id
    WHERE DATE(s.sale_date) BETWEEN ? AND ?
        AND s.status != 'cancelled'
    ";
    
    $params = [$start_date, $end_date];
    
    // Add shop filter if specified
    if($shop_id && $shop_id != 0){
        $sql .= " AND s.shop_id = ?";
        $params[] = $shop_id;
    } elseif ($user_role !== 'admin' && $user_shop_id) {
        $sql .= " AND s.shop_id = ?";
        $params[] = $user_shop_id;
    }
    
    $sql .= " GROUP BY DATE(s.sale_date), s.shop_id, sh.name ORDER BY sale_day DESC, shop_name";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $daily_summary = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Calculate totals
    $total_invoices = 0;
    $total_quantity = 0;
    $total_gross = 0;
    $total_discount = 0;
    $total_net = 0;
    $total_paid = 0;
    $total_outstanding = 0;
    
    foreach($daily_summary as $row){
        $total_invoices += $row['invoice_count'];
        $total_quantity += $row['total_quantity'];
        $total_gross += $row['gross_amount'];
        $total_discount += $row['total_discount'];
        $total_net += $row['net_amount'];
        $total_paid += $row['total_paid'];
        $total_outstanding += $row['outstanding_amount'];
    }
    
    // Get shop name for CSV header
    $shop_name = 'All Shops';
    if($shop_id && $shop_id != 0){
        $stmt = $pdo->prepare("SELECT name FROM shops WHERE id = ?");
        $stmt->execute([$shop_id]);
        $shop = $stmt->fetch(PDO::FETCH_ASSOC);
        $shop_name = $shop['name'] ?? 'Unknown Shop';
    }
    
    // Output CSV
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=sales_summary_' . $start_date . '_to_' . $end_date . '.csv');
    
    $output = fopen('php://output', 'w');
    
    // Add BOM for UTF-8
    fwrite($output, "\xEF\xBB\xBF");
    
    // Header
    fputcsv($output, ['Daily Sales Summary Report']);
    fputcsv($output, ['Period:', $start_date . ' to ' . $end_date]);
    fputcsv($output, ['Shop:', $shop_name]);
    fputcsv($output, ['Generated:', date('Y-m-d H:i:s')]);
    fputcsv($output, []); // Empty line
    
    // Summary header
    fputcsv($output, ['Date', 'Shop', 'Invoices', 'Customers', 'Quantity', 'Gross Amount', 'Discount', 'Net Amount', 'Amount Paid', 'Outstanding']);
    
    // Data rows
    foreach($daily_summary as $row){
        fputcsv($output, [
            $row['sale_day'],
            $row['shop_name'],
            $row['invoice_count'],
            $row['customer_count'],
            $row['total_quantity'],
            $row['gross_amount'], // Don't format here - keep as number
            $row['total_discount'],
            $row['net_amount'],
            $row['total_paid'],
            $row['outstanding_amount']
        ]);
    }
    
    // Totals row
    fputcsv($output, [
        'TOTAL',
        '',
        $total_invoices,
        '',
        $total_quantity,
        $total_gross,
        $total_discount,
        $total_net,
        $total_paid,
        $total_outstanding
    ]);
    
    fclose($output);
    exit;
}

// Only load the full page if not exporting
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

if (!isset($_SESSION['user'])) { 
    echo "Access denied"; 
    exit; 
}

$user_role = $_SESSION['user']['role'] ?? '';
$user_shop_id = $_SESSION['user']['shop_id'] ?? 0;
$user_id = $_SESSION['user']['id'] ?? 0;

// Get date range (default to today)
$start_date = $_GET['start_date'] ?? date('Y-m-d');
$end_date = $_GET['end_date'] ?? date('Y-m-d');
$shop_id = $_GET['shop_id'] ?? 0;

// ===== SHOP HANDLING =====
if($user_role === 'admin') {
    // Admin can see all shops
    $shops = $pdo->query("SELECT id, name FROM shops ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
    $shop_id = $_GET['shop_id'] ?? 0; // 0 = all shops
} else {
    // Non-admin: only their assigned shop
    $shops = [];
    if($user_shop_id){
        $stmt = $pdo->prepare("SELECT id, name FROM shops WHERE id=?");
        $stmt->execute([$user_shop_id]);
        $shops = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $shop_id = $user_shop_id; // force filter
    } else {
        echo "<div class='alert alert-danger'>No shop assigned to your account.</div>";
        require_once '../includes/footer.php';
        exit;
    }
}

// ===== FETCH SALES SUMMARY =====
$sql = "
SELECT 
    DATE(s.sale_date) as sale_day,
    COUNT(DISTINCT s.id) as invoice_count,
    COUNT(DISTINCT s.customer_id) as customer_count,
    SUM(sl.qty) as total_quantity,
    SUM(sl.qty * sl.unit_price) as gross_amount,
    SUM(sl.discount) as total_discount,
    SUM(sl.line_total) as net_amount,
    SUM(COALESCE(p.amount, 0)) as total_paid,
    AVG(sl.unit_price) as avg_price,
    GREATEST(SUM(s.total - COALESCE(p.amount, 0)), 0) as outstanding_amount,
    s.shop_id,
    sh.name as shop_name
FROM sales s
LEFT JOIN sale_lines sl ON s.id = sl.sale_id
LEFT JOIN (
    SELECT sale_id, SUM(amount) as amount 
    FROM payments 
    GROUP BY sale_id
) p ON s.id = p.sale_id
LEFT JOIN shops sh ON s.shop_id = sh.id
WHERE DATE(s.sale_date) BETWEEN ? AND ?
    AND s.status != 'cancelled'
";

$params = [$start_date, $end_date];

// Add shop filter if specified
if($shop_id && $shop_id != 0){
    $sql .= " AND s.shop_id = ?";
    $params[] = $shop_id;
} elseif ($user_role !== 'admin' && $user_shop_id) {
    // Non-admin users: restrict to their shop
    $sql .= " AND s.shop_id = ?";
    $params[] = $user_shop_id;
}

$sql .= " GROUP BY DATE(s.sale_date), s.shop_id, sh.name ORDER BY sale_day DESC, shop_name";

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

// ===== TOTALS =====
$total_invoices = 0;
$total_quantity = 0;
$total_gross = 0;
$total_discount = 0;
$total_net = 0;
$total_paid = 0;
$total_outstanding = 0;

foreach($daily_summary as $row){
    $total_invoices += $row['invoice_count'];
    $total_quantity += $row['total_quantity'];
    $total_gross += $row['gross_amount'];
    $total_discount += $row['total_discount'];
    $total_net += $row['net_amount'];
    $total_paid += $row['total_paid'];
    $total_outstanding += $row['outstanding_amount'];
}

// ===== TOP PRODUCTS FOR THE PERIOD =====
$top_products_sql = "
SELECT 
    p.name,
    p.sku,
    p.category,
    SUM(sl.qty) as quantity_sold,
    SUM(sl.line_total) as total_amount,
    AVG(sl.unit_price) as avg_price
FROM sale_lines sl
JOIN products p ON sl.product_id = p.id
JOIN sales s ON sl.sale_id = s.id
WHERE DATE(s.sale_date) BETWEEN ? AND ?
    AND s.status != 'cancelled'
";

$top_params = [$start_date, $end_date];

if($shop_id && $shop_id != 0){
    $top_products_sql .= " AND s.shop_id = ?";
    $top_params[] = $shop_id;
} elseif ($user_role !== 'admin' && $user_shop_id) {
    $top_products_sql .= " AND s.shop_id = ?";
    $top_params[] = $user_shop_id;
}

$top_products_sql .= " GROUP BY p.id, p.name, p.sku, p.category ORDER BY quantity_sold DESC LIMIT 10";

$top_stmt = $pdo->prepare($top_products_sql);
$top_stmt->execute($top_params);
$top_products = $top_stmt->fetchAll(PDO::FETCH_ASSOC);

?>
<style>
    @media print {
        .sidebar, .navbar, .btn, form, .no-print {
            display: none !important;
        }
        body {
            margin: 0;
            background: white;
        }
        .print-only {
            display: block !important;
        }
        table {
            font-size: 11px;
            width: 100%;
        }
        h3, h4 {
            margin: 5px 0;
        }
    }
    .print-only {
        display: none;
    }
    .summary-card {
        border: 1px solid #ddd;
        border-radius: 5px;
        padding: 15px;
        margin-bottom: 15px;
        background: #f8f9fa;
    }
    .table th {
        background-color: #f1f1f1;
    }
    .text-green { color: #28a745; }
    .text-red { color: #dc3545; }
    .text-orange { color: #fd7e14; }
</style>

<div class="col-md-10 ml-sm-auto px-4 py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="text-success">Daily Sales Summary</h3>
        <div class="no-print">
            <button onclick="window.print()" class="btn btn-primary btn-sm mr-2">
                <i class="fa fa-print"></i> Print
            </button>
            <a href="?export=csv&start_date=<?= $start_date ?>&end_date=<?= $end_date ?>&shop_id=<?= $shop_id ?>" 
               class="btn btn-success btn-sm">
                <i class="fa fa-download"></i> Export CSV
            </a>
        </div>
    </div>

    <!-- Date and Shop Filter Form -->
    <form method="get" class="mb-4 no-print">
        <div class="form-row">
            <div class="form-group col-md-3">
                <label>Start Date</label>
                <input type="date" name="start_date" value="<?= htmlspecialchars($start_date) ?>" 
                       class="form-control form-control-sm">
            </div>
            <div class="form-group col-md-3">
                <label>End Date</label>
                <input type="date" name="end_date" value="<?= htmlspecialchars($end_date) ?>" 
                       class="form-control form-control-sm">
            </div>
            <?php if($user_role === 'admin'): ?>
            <div class="form-group col-md-3">
                <label>Shop</label>
                <select name="shop_id" class="form-control form-control-sm">
                    <option value="0">All Shops</option>
                    <?php foreach($shops as $s): ?>
                        <option value="<?= $s['id'] ?>" <?= $shop_id==$s['id']?'selected':'' ?>>
                            <?= htmlspecialchars($s['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php else: ?>
                <input type="hidden" name="shop_id" value="<?= $shop_id ?>">
            <?php endif; ?>
            <div class="form-group col-md-3">
                <label>&nbsp;</label><br>
                <button type="submit" class="btn btn-primary btn-sm">Filter</button>
                <a href="sales_daily.php" class="btn btn-secondary btn-sm">Reset</a>
            </div>
        </div>
    </form>

    <!-- Print Header -->
    <div class="print-only mb-4">
        <h3>Daily Sales Summary Report</h3>
        <p>Period: <?= htmlspecialchars($start_date) ?> to <?= htmlspecialchars($end_date) ?></p>
        <p>Shop: <?= ($shop_id && $shop_id!=0) ? htmlspecialchars($shops[0]['name'] ?? '') : 'All Shops' ?></p>
        <p>Generated: <?= date('Y-m-d H:i:s') ?></p>
        <hr>
    </div>

    <!-- Summary Cards -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="summary-card text-center">
                <h5 class="text-muted">Total Invoices</h5>
                <h3 class="text-primary"><?= number_format($total_invoices) ?></h3>
            </div>
        </div>
        <div class="col-md-3">
            <div class="summary-card text-center">
                <h5 class="text-muted">Total Quantity</h5>
                <h3 class="text-info"><?= number_format($total_quantity) ?></h3>
            </div>
        </div>
        <div class="col-md-3">
            <div class="summary-card text-center">
                <h5 class="text-muted">Net Amount</h5>
                <h3 class="text-success"><?= number_format($total_net, 2) ?></h3>
            </div>
        </div>
        <div class="col-md-3">
            <div class="summary-card text-center">
                <h5 class="text-muted">Outstanding</h5>
                <h3 class="<?= $total_outstanding > 0 ? 'text-warning' : 'text-green' ?>">
                    <?= number_format($total_outstanding, 2) ?>
                </h3>
            </div>
        </div>
    </div>

    <!-- Daily Summary Table -->
    <h4 class="mb-3">Daily Breakdown</h4>
    <div class="table-responsive">
        <table class="table table-bordered table-hover table-sm">
            <thead class="thead-light">
                <tr>
                    <th>Date</th>
                    <?php if($user_role === 'admin' && $shop_id == 0): ?>
                    <th>Shop</th>
                    <?php endif; ?>
                    <th>Invoices</th>
                    <th>Customers</th>
                    <th>Quantity</th>
                    <th>Gross Amount</th>
                    <th>Discount</th>
                    <th>Net Amount</th>
                    <th>Amount Paid</th>
                    <th>Outstanding</th>
                    <th>Avg Price</th>
                </tr>
            </thead>
            <tbody>
                <?php if(empty($daily_summary)): ?>
                <tr>
                    <td colspan="<?= $user_role === 'admin' && $shop_id == 0 ? 11 : 10 ?>" class="text-center">
                        No sales data found for the selected period
                    </td>
                </tr>
                <?php else: ?>
                <?php foreach($daily_summary as $row): ?>
                <tr>
                    <td><?= htmlspecialchars($row['sale_day']) ?></td>
                    <?php if($user_role === 'admin' && $shop_id == 0): ?>
                    <td><?= htmlspecialchars($row['shop_name']) ?></td>
                    <?php endif; ?>
                    <td class="text-right"><?= number_format($row['invoice_count']) ?></td>
                    <td class="text-right"><?= number_format($row['customer_count']) ?></td>
                    <td class="text-right"><?= number_format($row['total_quantity']) ?></td>
                    <td class="text-right"><?= number_format($row['gross_amount'], 2) ?></td>
                    <td class="text-right"><?= number_format($row['total_discount'], 2) ?></td>
                    <td class="text-right"><?= number_format($row['net_amount'], 2) ?></td>
                    <td class="text-right"><?= number_format($row['total_paid'], 2) ?></td>
                    <td class="text-right <?= ($row['outstanding_amount'] > 0) ? 'text-warning' : (($row['outstanding_amount'] < 0) ? 'text-orange' : 'text-green') ?>">
                        <?= number_format($row['outstanding_amount'], 2) ?>
                    </td>
                    <td class="text-right"><?= number_format($row['avg_price'] ?? 0, 2) ?></td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
            <tfoot class="font-weight-bold">
                <tr>
                    <td>TOTAL</td>
                    <?php if($user_role === 'admin' && $shop_id == 0): ?>
                    <td></td>
                    <?php endif; ?>
                    <td class="text-right"><?= number_format($total_invoices) ?></td>
                    <td></td>
                    <td class="text-right"><?= number_format($total_quantity) ?></td>
                    <td class="text-right"><?= number_format($total_gross, 2) ?></td>
                    <td class="text-right"><?= number_format($total_discount, 2) ?></td>
                    <td class="text-right"><?= number_format($total_net, 2) ?></td>
                    <td class="text-right"><?= number_format($total_paid, 2) ?></td>
                    <td class="text-right <?= $total_outstanding > 0 ? 'text-warning' : 'text-green' ?>">
                        <?= number_format($total_outstanding, 2) ?>
                    </td>
                    <td></td>
                </tr>
            </tfoot>
        </table>
    </div>

    <!-- Top Products -->
    <?php if(!empty($top_products)): ?>
    <h4 class="mt-5 mb-3">Top 10 Products</h4>
    <div class="table-responsive">
        <table class="table table-bordered table-sm">
            <thead class="thead-light">
                <tr>
                    <th>Product</th>
                    <th>SKU</th>
                    <th>Category</th>
                    <th>Quantity Sold</th>
                    <th>Total Amount</th>
                    <th>Average Price</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($top_products as $product): ?>
                <tr>
                    <td><?= htmlspecialchars($product['name']) ?></td>
                    <td><?= htmlspecialchars($product['sku']) ?></td>
                    <td><?= htmlspecialchars($product['category']) ?></td>
                    <td class="text-right"><?= number_format($product['quantity_sold']) ?></td>
                    <td class="text-right"><?= number_format($product['total_amount'], 2) ?></td>
                    <td class="text-right"><?= number_format($product['avg_price'], 2) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<?php require_once '../includes/footer.php'; ?>