<?php
/**
 * Payments Report
 * LandSales Pro - Detailed payments 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'] ?? '';
$method = $_GET['method'] ?? '';

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

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

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

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

// Get payments
$payments = db_fetch_all("SELECT py.*, s.sale_number, b.full_name as buyer_name,
    p.plot_number, pr.name as project_name
    FROM payments py
    JOIN sales s ON py.sale_id = s.id
    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 py.payment_date DESC", $types, $params);

// Calculate totals
$totalPayments = count($payments);
$totalAmount = array_sum(array_column($payments, 'amount'));

// Payments by method
$paymentsByMethod = db_fetch_all("SELECT py.payment_method, COUNT(*) as count, SUM(py.amount) as value
    FROM payments py
    JOIN sales s ON py.sale_id = s.id
    JOIN plots p ON s.plot_id = p.id
    JOIN projects pr ON p.project_id = pr.id
    {$whereClause}
    GROUP BY py.payment_method ORDER BY value DESC", $types, $params);

// Payments by project
$paymentsByProject = db_fetch_all("SELECT pr.name, COUNT(py.id) as count, SUM(py.amount) as value
    FROM payments py
    JOIN sales s ON py.sale_id = s.id
    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);

// Daily payments for chart
$dailyPayments = db_fetch_all("SELECT DATE(py.payment_date) as date, SUM(py.amount) as value
    FROM payments py
    JOIN sales s ON py.sale_id = s.id
    JOIN plots p ON s.plot_id = p.id
    JOIN projects pr ON p.project_id = pr.id
    {$whereClause}
    GROUP BY DATE(py.payment_date) ORDER BY date", $types, $params);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payments 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">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</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">Payments 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>Method</label>
                        <select name="method" class="form-control">
                            <option value="">All Methods</option>
                            <option value="cash" <?php echo $method === 'cash' ? 'selected' : ''; ?>>Cash</option>
                            <option value="bank" <?php echo $method === 'bank' ? 'selected' : ''; ?>>Bank Transfer</option>
                            <option value="mobile" <?php echo $method === 'mobile' ? 'selected' : ''; ?>>Mobile Money</option>
                            <option value="cheque" <?php echo $method === 'cheque' ? 'selected' : ''; ?>>Cheque</option>
                        </select>
                    </div>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-filter"></i> Filter
                    </button>
                </form>
            </div>

            <!-- Summary Stats -->
            <div class="stats-row">
                <div class="stat-mini success">
                    <i class="fas fa-money-bill-wave"></i>
                    <div>
                        <div class="stat-value">TZS <?php echo formatMoney($totalAmount); ?></div>
                        <div class="stat-label">Total Collected</div>
                    </div>
                </div>
                <div class="stat-mini info">
                    <i class="fas fa-receipt"></i>
                    <div>
                        <div class="stat-value"><?php echo number_format($totalPayments); ?></div>
                        <div class="stat-label">Total Payments</div>
                    </div>
                </div>
                <div class="stat-mini">
                    <i class="fas fa-calculator"></i>
                    <div>
                        <div class="stat-value">TZS <?php echo $totalPayments > 0 ? formatMoney($totalAmount / $totalPayments) : '0'; ?></div>
                        <div class="stat-label">Average Payment</div>
                    </div>
                </div>
            </div>

            <!-- Chart -->
            <?php if (!empty($dailyPayments)): ?>
            <div class="card no-print">
                <div class="card-header">
                    <h3><i class="fas fa-chart-area"></i> Daily Collections</h3>
                </div>
                <div class="card-body">
                    <canvas id="paymentsChart" height="200"></canvas>
                </div>
            </div>
            <?php endif; ?>

            <!-- Summary Tables -->
            <div class="summary-grid">
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-credit-card"></i> By Payment Method</h3>
                    </div>
                    <div class="card-body">
                        <table class="summary-table">
                            <thead>
                                <tr>
                                    <th>Method</th>
                                    <th>Count</th>
                                    <th>Amount</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($paymentsByMethod as $item): ?>
                                <tr>
                                    <td>
                                        <span class="method-badge method-<?php echo $item['payment_method']; ?>">
                                            <?php echo ucfirst($item['payment_method']); ?>
                                        </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 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>Count</th>
                                    <th>Amount</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($paymentsByProject 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>

            <!-- Detailed Payments Table -->
            <div class="card">
                <div class="card-header">
                    <h3><i class="fas fa-list"></i> Payment Details</h3>
                </div>
                <div class="table-responsive">
                    <table class="data-table" id="paymentsTable">
                        <thead>
                            <tr>
                                <th>Payment #</th>
                                <th>Date</th>
                                <th>Buyer</th>
                                <th>Plot</th>
                                <th>Project</th>
                                <th>Method</th>
                                <th>Amount</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($payments)): ?>
                            <tr>
                                <td colspan="7" class="empty-row">
                                    <div class="empty-state">
                                        <i class="fas fa-money-bill-wave"></i>
                                        <p>No payments found for the selected period</p>
                                    </div>
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($payments as $payment): ?>
                            <tr>
                                <td><?php echo $payment['payment_number']; ?></td>
                                <td><?php echo date('M j, Y', strtotime($payment['payment_date'])); ?></td>
                                <td><?php echo htmlspecialchars($payment['buyer_name']); ?></td>
                                <td><?php echo $payment['plot_number']; ?></td>
                                <td><?php echo htmlspecialchars($payment['project_name']); ?></td>
                                <td>
                                    <span class="method-badge method-<?php echo $payment['payment_method']; ?>">
                                        <?php echo ucfirst($payment['payment_method']); ?>
                                    </span>
                                </td>
                                <td class="text-success">TZS <?php echo number_format($payment['amount']); ?></td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                        <tfoot>
                            <tr class="total-row">
                                <td colspan="6"><strong>TOTAL</strong></td>
                                <td><strong>TZS <?php echo number_format($totalAmount); ?></strong></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; }

        .stats-row { display: flex; gap: 1rem; margin-bottom: 1.5rem; flex-wrap: wrap; }
        .stat-mini { flex: 1; min-width: 200px; 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 .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; margin-bottom: 1.5rem; }
        .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; }

        .method-badge { padding: 0.25rem 0.5rem; border-radius: 4px; font-size: 0.7rem; font-weight: 500; background: #f1f5f9; color: #64748b; }
        .method-cash { background: #dcfce7; color: #16a34a; }
        .method-bank { background: #dbeafe; color: #2563eb; }
        .method-mobile { background: #fef3c7; color: #d97706; }
        .method-cheque { background: #f3e8ff; color: #9333ea; }

        .text-success { color: #16a34a; font-weight: 600; }

        .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; }
            .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>
        <?php if (!empty($dailyPayments)): ?>
        const ctx = document.getElementById('paymentsChart').getContext('2d');
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: <?php echo json_encode(array_map(function($d) { return date('M j', strtotime($d['date'])); }, $dailyPayments)); ?>,
                datasets: [{
                    label: 'Collections',
                    data: <?php echo json_encode(array_column($dailyPayments, 'value')); ?>,
                    borderColor: '#22c55e',
                    backgroundColor: 'rgba(34, 197, 94, 0.1)',
                    fill: true,
                    tension: 0.4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return 'TZS ' + (value / 1000000).toFixed(1) + 'M';
                            }
                        }
                    }
                }
            }
        });
        <?php endif; ?>

        function exportToCSV() {
            const table = document.getElementById('paymentsTable');
            const rows = table.querySelectorAll('tbody tr');
            let csv = 'Payment #,Date,Buyer,Plot,Project,Method,Amount\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 = 'payments_report_<?php echo date('Y-m-d'); ?>.csv';
            a.click();
        }
    </script>
</body>
</html>
