<?php
/**
 * Sales Report
 * LandSales Pro - Detailed sales analysis
 */
define('APP_RUNNING', true);
require_once '../../db_connect.php';
require_once '../../includes/auth.php';
require_once '../../includes/subscription.php';
require_once '../../includes/functions.php';

initSecureSession();
requireAuth();
requireSubscription();

$userId = $_SESSION['user_id'];

// Filters
$dateFrom = $_GET['from'] ?? date('Y-m-01');
$dateTo = $_GET['to'] ?? date('Y-m-d');
$projectId = $_GET['project'] ?? '';
$status = $_GET['status'] ?? '';

// Get projects for filter
$projects = db_fetch_all("SELECT * FROM projects WHERE user_id = ? ORDER BY name", 'i', [$userId]);

// Build query
$whereClause = "WHERE s.user_id = ? AND s.sale_date >= ? AND s.sale_date <= ?";
$params = [$userId, $dateFrom, $dateTo];
$types = 'iss';

if ($projectId) {
    $whereClause .= " AND p.project_id = ?";
    $params[] = intval($projectId);
    $types .= 'i';
}

if ($status) {
    $whereClause .= " AND s.status = ?";
    $params[] = $status;
    $types .= 's';
}

// Get sales
$sales = db_fetch_all("SELECT s.*, b.full_name as buyer_name, b.phone as buyer_phone,
    p.plot_number, pr.name as project_name,
    (SELECT COALESCE(SUM(amount), 0) FROM payments WHERE sale_id = s.id AND status = 'confirmed') as total_paid
    FROM sales s
    JOIN buyers b ON s.buyer_id = b.id
    JOIN plots p ON s.plot_id = p.id
    JOIN projects pr ON p.project_id = pr.id
    {$whereClause}
    ORDER BY s.sale_date DESC", $types, $params);

// Calculate totals
$totalSales = count($sales);
$totalValue = array_sum(array_column($sales, 'total_price'));
$totalPaid = array_sum(array_column($sales, 'total_paid'));
$totalBalance = $totalValue - $totalPaid;

// Sales by project
$salesByProject = db_fetch_all("SELECT pr.name, COUNT(s.id) as count, SUM(s.total_price) as value
    FROM sales s
    JOIN plots p ON s.plot_id = p.id
    JOIN projects pr ON p.project_id = pr.id
    {$whereClause}
    GROUP BY pr.id ORDER BY value DESC", $types, $params);

// Sales by status
$salesByStatus = db_fetch_all("SELECT s.status, COUNT(*) as count, SUM(s.total_price) as value
    FROM sales s
    JOIN plots p ON s.plot_id = p.id
    {$whereClause}
    GROUP BY s.status", $types, $params);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sales Report - <?php echo APP_NAME; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/font-awesome/css/all.min.css">
</head>
<body>
    <?php include '../includes/sidebar.php'; ?>

    <div class="main-content">
        <div class="top-header">
            <button class="menu-toggle" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
            <h1 class="page-title">Sales Report</h1>
            <div class="header-actions">
                <a href="index.php" class="btn btn-outline">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
                <button onclick="window.print()" class="btn btn-outline">
                    <i class="fas fa-print"></i> Print
                </button>
                <button onclick="exportToCSV()" class="btn btn-primary">
                    <i class="fas fa-download"></i> Export CSV
                </button>
            </div>
        </div>

        <div class="content-wrapper">
            <!-- Filters -->
            <div class="filters-card no-print">
                <form class="filters-form" method="GET">
                    <div class="filter-group">
                        <label>From</label>
                        <input type="date" name="from" class="form-control" value="<?php echo $dateFrom; ?>">
                    </div>
                    <div class="filter-group">
                        <label>To</label>
                        <input type="date" name="to" class="form-control" value="<?php echo $dateTo; ?>">
                    </div>
                    <div class="filter-group">
                        <label>Project</label>
                        <select name="project" class="form-control">
                            <option value="">All Projects</option>
                            <?php foreach ($projects as $project): ?>
                            <option value="<?php echo $project['id']; ?>" <?php echo $projectId == $project['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($project['name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label>Status</label>
                        <select name="status" class="form-control">
                            <option value="">All Status</option>
                            <option value="active" <?php echo $status === 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="completed" <?php echo $status === 'completed' ? 'selected' : ''; ?>>Completed</option>
                            <option value="cancelled" <?php echo $status === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                        </select>
                    </div>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-filter"></i> Filter
                    </button>
                </form>
            </div>

            <!-- Report Header -->
            <div class="report-header print-only">
                <h2>Sales Report</h2>
                <p>Period: <?php echo date('M j, Y', strtotime($dateFrom)); ?> - <?php echo date('M j, Y', strtotime($dateTo)); ?></p>
            </div>

            <!-- Summary Stats -->
            <div class="stats-row">
                <div class="stat-mini">
                    <i class="fas fa-handshake"></i>
                    <div>
                        <div class="stat-value"><?php echo number_format($totalSales); ?></div>
                        <div class="stat-label">Total Sales</div>
                    </div>
                </div>
                <div class="stat-mini success">
                    <i class="fas fa-chart-line"></i>
                    <div>
                        <div class="stat-value">TZS <?php echo formatMoney($totalValue); ?></div>
                        <div class="stat-label">Total Value</div>
                    </div>
                </div>
                <div class="stat-mini info">
                    <i class="fas fa-money-bill-wave"></i>
                    <div>
                        <div class="stat-value">TZS <?php echo formatMoney($totalPaid); ?></div>
                        <div class="stat-label">Collected</div>
                    </div>
                </div>
                <div class="stat-mini warning">
                    <i class="fas fa-clock"></i>
                    <div>
                        <div class="stat-value">TZS <?php echo formatMoney($totalBalance); ?></div>
                        <div class="stat-label">Outstanding</div>
                    </div>
                </div>
            </div>

            <!-- Summary Tables -->
            <div class="summary-grid no-print">
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-building"></i> By Project</h3>
                    </div>
                    <div class="card-body">
                        <table class="summary-table">
                            <thead>
                                <tr>
                                    <th>Project</th>
                                    <th>Sales</th>
                                    <th>Value</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($salesByProject as $item): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($item['name']); ?></td>
                                    <td><?php echo $item['count']; ?></td>
                                    <td>TZS <?php echo number_format($item['value']); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-tags"></i> By Status</h3>
                    </div>
                    <div class="card-body">
                        <table class="summary-table">
                            <thead>
                                <tr>
                                    <th>Status</th>
                                    <th>Sales</th>
                                    <th>Value</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($salesByStatus as $item): ?>
                                <tr>
                                    <td><span class="status-badge status-<?php echo $item['status']; ?>"><?php echo ucfirst($item['status']); ?></span></td>
                                    <td><?php echo $item['count']; ?></td>
                                    <td>TZS <?php echo number_format($item['value']); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Detailed Sales Table -->
            <div class="card">
                <div class="card-header">
                    <h3><i class="fas fa-list"></i> Sales Details</h3>
                </div>
                <div class="table-responsive">
                    <table class="data-table" id="salesTable">
                        <thead>
                            <tr>
                                <th>Sale #</th>
                                <th>Date</th>
                                <th>Buyer</th>
                                <th>Plot</th>
                                <th>Project</th>
                                <th>Total Price</th>
                                <th>Paid</th>
                                <th>Balance</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($sales)): ?>
                            <tr>
                                <td colspan="9" class="empty-row">
                                    <div class="empty-state">
                                        <i class="fas fa-chart-bar"></i>
                                        <p>No sales found for the selected period</p>
                                    </div>
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($sales as $sale):
                                $balance = $sale['total_price'] - $sale['total_paid'];
                            ?>
                            <tr>
                                <td><?php echo $sale['sale_number']; ?></td>
                                <td><?php echo date('M j, Y', strtotime($sale['sale_date'])); ?></td>
                                <td><?php echo htmlspecialchars($sale['buyer_name']); ?></td>
                                <td><?php echo $sale['plot_number']; ?></td>
                                <td><?php echo htmlspecialchars($sale['project_name']); ?></td>
                                <td>TZS <?php echo number_format($sale['total_price']); ?></td>
                                <td class="text-success">TZS <?php echo number_format($sale['total_paid']); ?></td>
                                <td class="<?php echo $balance > 0 ? 'text-warning' : 'text-success'; ?>">
                                    TZS <?php echo number_format($balance); ?>
                                </td>
                                <td>
                                    <span class="status-badge status-<?php echo $sale['status']; ?>">
                                        <?php echo ucfirst($sale['status']); ?>
                                    </span>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                        <tfoot>
                            <tr class="total-row">
                                <td colspan="5"><strong>TOTAL</strong></td>
                                <td><strong>TZS <?php echo number_format($totalValue); ?></strong></td>
                                <td><strong>TZS <?php echo number_format($totalPaid); ?></strong></td>
                                <td><strong>TZS <?php echo number_format($totalBalance); ?></strong></td>
                                <td></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <style>
        body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; margin: 0; background: #f1f5f9; }
        .header-actions { display: flex; gap: 0.75rem; }
        .btn { padding: 0.625rem 1.25rem; border-radius: 8px; font-weight: 500; text-decoration: none; display: inline-flex; align-items: center; gap: 0.5rem; transition: all 0.2s; border: none; cursor: pointer; font-size: 0.875rem; }
        .btn-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .btn-outline { border: 1px solid #e2e8f0; background: white; color: #64748b; }

        .filters-card { background: white; border-radius: 10px; padding: 1rem; margin-bottom: 1.5rem; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
        .filters-form { display: flex; gap: 1rem; flex-wrap: wrap; align-items: flex-end; }
        .filter-group { display: flex; flex-direction: column; gap: 0.25rem; }
        .filter-group label { font-size: 0.85rem; font-weight: 500; color: #64748b; }
        .form-control { padding: 0.5rem 0.75rem; border: 1px solid #e2e8f0; border-radius: 6px; font-size: 0.85rem; }

        .report-header { display: none; text-align: center; margin-bottom: 1.5rem; }
        .report-header h2 { margin: 0; }
        .report-header p { margin: 0.5rem 0 0; color: #64748b; }

        .stats-row { display: flex; gap: 1rem; margin-bottom: 1.5rem; flex-wrap: wrap; }
        .stat-mini { flex: 1; min-width: 180px; padding: 1rem; background: white; border-radius: 10px; display: flex; align-items: center; gap: 0.75rem; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
        .stat-mini i { width: 40px; height: 40px; background: #f1f5f9; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: #64748b; }
        .stat-mini.success { border-left: 3px solid #22c55e; }
        .stat-mini.success i { background: #dcfce7; color: #16a34a; }
        .stat-mini.info { border-left: 3px solid #3b82f6; }
        .stat-mini.info i { background: #dbeafe; color: #2563eb; }
        .stat-mini.warning { border-left: 3px solid #f59e0b; }
        .stat-mini.warning i { background: #fef3c7; color: #d97706; }
        .stat-mini .stat-value { font-size: 1.1rem; font-weight: 700; color: #1e293b; }
        .stat-mini .stat-label { font-size: 0.75rem; color: #64748b; }

        .summary-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 1.5rem; margin-bottom: 1.5rem; }
        .summary-table { width: 100%; border-collapse: collapse; }
        .summary-table th, .summary-table td { padding: 0.75rem; text-align: left; border-bottom: 1px solid #f1f5f9; }
        .summary-table th { font-size: 0.75rem; text-transform: uppercase; color: #64748b; }

        .card { background: white; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden; }
        .card-header { padding: 1rem 1.25rem; border-bottom: 1px solid #f1f5f9; background: #f8fafc; }
        .card-header h3 { margin: 0; font-size: 0.95rem; font-weight: 600; color: #1e293b; display: flex; align-items: center; gap: 0.5rem; }
        .card-header h3 i { color: #667eea; }
        .card-body { padding: 1.25rem; }

        .table-responsive { overflow-x: auto; }
        .data-table { width: 100%; border-collapse: collapse; }
        .data-table th, .data-table td { padding: 0.75rem 1rem; text-align: left; border-bottom: 1px solid #f1f5f9; font-size: 0.85rem; }
        .data-table th { background: #f8fafc; font-weight: 600; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.5px; color: #64748b; }
        .data-table tbody tr:hover { background: #f8fafc; }
        .total-row { background: #f8fafc; }
        .total-row td { border-top: 2px solid #667eea; }

        .status-badge { padding: 0.25rem 0.5rem; border-radius: 4px; font-size: 0.7rem; font-weight: 600; }
        .status-active { background: #dbeafe; color: #2563eb; }
        .status-completed { background: #dcfce7; color: #16a34a; }
        .status-cancelled { background: #fee2e2; color: #dc2626; }

        .text-success { color: #16a34a; }
        .text-warning { color: #d97706; }

        .empty-row td { padding: 3rem; }
        .empty-state { text-align: center; color: #94a3b8; }
        .empty-state i { font-size: 2rem; margin-bottom: 0.5rem; }

        @media print {
            body { background: white; }
            .no-print { display: none !important; }
            .print-only { display: block !important; }
            .report-header { display: block; }
            .sidebar, .top-header { display: none; }
            .main-content { margin-left: 0; padding: 0; }
            .card { box-shadow: none; border: 1px solid #e2e8f0; }
        }

        @media (max-width: 768px) {
            .stats-row { flex-direction: column; }
            .summary-grid { grid-template-columns: 1fr; }
            .filters-form { flex-direction: column; }
        }
    </style>

    <script>
        function exportToCSV() {
            const table = document.getElementById('salesTable');
            const rows = table.querySelectorAll('tbody tr');
            let csv = 'Sale #,Date,Buyer,Plot,Project,Total Price,Paid,Balance,Status\n';

            rows.forEach(row => {
                const cells = row.querySelectorAll('td');
                if (cells.length > 1) {
                    const rowData = Array.from(cells).map(cell => {
                        let text = cell.textContent.trim().replace(/,/g, '');
                        return '"' + text + '"';
                    });
                    csv += rowData.join(',') + '\n';
                }
            });

            const blob = new Blob([csv], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'sales_report_<?php echo date('Y-m-d'); ?>.csv';
            a.click();
        }
    </script>
</body>
</html>
