<?php
/**
 * ============================================================================
 * buyer/reports.php
 * Reports Generator - Custom business reports with export
 * ============================================================================
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/BuyerSystem.php';

if (!isLoggedIn() || getUserType() !== 'buyer') {
    header('Location: ' . APP_URL . '/auth/login.php');
    exit();
}

use App\Database;
$database = Database::getInstance();
$db = $database->getConnection();
$currentUserId = getUserId();
$buyerSystem = new BuyerSystem($database, $currentUserId);

if (!$buyerSystem->hasPermission('export_reports')) {
    $_SESSION['flash_message'] = 'Reports are only available for verified premium buyers';
    $_SESSION['flash_type'] = 'warning';
    header('Location: ' . APP_URL . '/buyer/dashboard.php');
    exit();
}

// Handle report generation
$reportData = null;
$reportType = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'generate_report') {
    $reportType = $_POST['report_type'];
    $fromDate = $_POST['from_date'];
    $toDate = $_POST['to_date'];
    
    switch ($reportType) {
        case 'purchase_summary':
            $sql = "SELECT p.category, p.product_name,
                           COUNT(o.id) as order_count,
                           SUM(o.quantity) as total_quantity,
                           AVG(o.unit_price) as avg_price,
                           SUM(o.total_amount) as total_spent,
                           MIN(o.unit_price) as min_price,
                           MAX(o.unit_price) as max_price
                    FROM orders o
                    INNER JOIN products p ON o.product_id = p.id
                    WHERE o.buyer_id = ? AND o.created_at BETWEEN ? AND ?
                    GROUP BY p.category, p.product_name
                    ORDER BY total_spent DESC";
            $stmt = $db->prepare($sql);
            $stmt->execute([$currentUserId, $fromDate, $toDate]);
            $reportData = $stmt->fetchAll(PDO::FETCH_ASSOC);
            break;
            
        case 'supplier_performance':
            $sql = "SELECT u.full_name, u.phone_number,
                           d.district_name,
                           COUNT(DISTINCT o.id) as total_orders,
                           SUM(o.total_amount) as total_spent,
                           AVG(o.total_amount) as avg_order_value,
                           COUNT(CASE WHEN o.status = 'completed' THEN 1 END) as completed_orders,
                           COUNT(CASE WHEN o.status = 'cancelled' THEN 1 END) as cancelled_orders,
                           ROUND(COUNT(CASE WHEN o.status = 'completed' THEN 1 END) * 100.0 / COUNT(*), 2) as completion_rate,
                           COALESCE(AVG(r.rating), 0) as avg_rating
                    FROM orders o
                    INNER JOIN users u ON o.seller_id = u.id
                    LEFT JOIN districts d ON u.district_id = d.id
                    LEFT JOIN reviews r ON o.id = r.order_id
                    WHERE o.buyer_id = ? AND o.created_at BETWEEN ? AND ?
                    GROUP BY u.id, u.full_name, u.phone_number, d.district_name
                    ORDER BY total_spent DESC";
            $stmt = $db->prepare($sql);
            $stmt->execute([$currentUserId, $fromDate, $toDate]);
            $reportData = $stmt->fetchAll(PDO::FETCH_ASSOC);
            break;
            
        case 'spending_analysis':
            $sql = "SELECT DATE_FORMAT(o.created_at, '%Y-%m') as month,
                           p.category,
                           COUNT(o.id) as order_count,
                           SUM(o.total_amount) as total_amount
                    FROM orders o
                    INNER JOIN products p ON o.product_id = p.id
                    WHERE o.buyer_id = ? AND o.created_at BETWEEN ? AND ?
                    GROUP BY DATE_FORMAT(o.created_at, '%Y-%m'), p.category
                    ORDER BY month DESC, total_amount DESC";
            $stmt = $db->prepare($sql);
            $stmt->execute([$currentUserId, $fromDate, $toDate]);
            $reportData = $stmt->fetchAll(PDO::FETCH_ASSOC);
            break;
            
        case 'order_status':
            $sql = "SELECT o.status,
                           COUNT(*) as count,
                           SUM(o.total_amount) as total_value,
                           AVG(o.total_amount) as avg_value,
                           MIN(o.created_at) as first_order,
                           MAX(o.created_at) as last_order
                    FROM orders o
                    WHERE o.buyer_id = ? AND o.created_at BETWEEN ? AND ?
                    GROUP BY o.status
                    ORDER BY count DESC";
            $stmt = $db->prepare($sql);
            $stmt->execute([$currentUserId, $fromDate, $toDate]);
            $reportData = $stmt->fetchAll(PDO::FETCH_ASSOC);
            break;
            
        case 'price_trends':
            $sql = "SELECT p.product_name, p.category,
                           DATE_FORMAT(o.created_at, '%Y-%m') as month,
                           AVG(o.unit_price) as avg_price,
                           MIN(o.unit_price) as min_price,
                           MAX(o.unit_price) as max_price,
                           COUNT(*) as purchase_count
                    FROM orders o
                    INNER JOIN products p ON o.product_id = p.id
                    WHERE o.buyer_id = ? AND o.created_at BETWEEN ? AND ?
                    GROUP BY p.product_name, p.category, DATE_FORMAT(o.created_at, '%Y-%m')
                    ORDER BY p.product_name, month DESC";
            $stmt = $db->prepare($sql);
            $stmt->execute([$currentUserId, $fromDate, $toDate]);
            $reportData = $stmt->fetchAll(PDO::FETCH_ASSOC);
            break;
    }
}

// Handle CSV export
if (isset($_GET['export']) && isset($_GET['type'])) {
    $exportType = $_GET['type'];
    $fromDate = $_GET['from'] ?? date('Y-m-01');
    $toDate = $_GET['to'] ?? date('Y-m-d');
    
    // Generate report data for export (same logic as above)
    // ... (code to fetch data based on exportType)
    
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="buyer_report_' . $exportType . '_' . date('Y-m-d') . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    if (!empty($reportData)) {
        // Write headers
        fputcsv($output, array_keys($reportData[0]));
        
        // Write data
        foreach ($reportData as $row) {
            fputcsv($output, $row);
        }
    }
    
    fclose($output);
    exit();
}

$pageTitle = 'Reports';
$breadcrumbs = [['title' => 'Reports', 'url' => '']];

require_once __DIR__ . '/includes/base.php';
require_once __DIR__ . '/includes/helpers.php';
renderBuyerHeader($pageTitle, $breadcrumbs);
?>

<style>
    .report-card {
        background: white;
        border-radius: 12px;
        padding: 1.5rem;
        box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        cursor: pointer;
        transition: all 0.3s ease;
        border: 2px solid transparent;
    }
    .report-card:hover {
        border-color: var(--primary-color);
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    }
    .report-card.active {
        border-color: var(--primary-color);
        background: linear-gradient(135deg, rgba(59, 130, 246, 0.05), rgba(59, 130, 246, 0.02));
    }
    .report-icon {
        font-size: 2.5rem;
        margin-bottom: 1rem;
    }
</style>

<div class="row mb-4">
    <div class="col">
        <h4><i class="bi bi-file-earmark-bar-graph me-2"></i>Generate Business Reports</h4>
        <p class="text-muted">Create detailed reports to analyze your purchasing activities</p>
    </div>
</div>

<!-- Report Type Selection -->
<div class="card shadow-sm mb-4">
    <div class="card-body">
        <h5 class="mb-3">Select Report Type</h5>
        
        <div class="row g-3">
            <div class="col-md-4">
                <div class="report-card" onclick="selectReport('purchase_summary')">
                    <div class="report-icon text-primary">
                        <i class="bi bi-cart-check"></i>
                    </div>
                    <h6>Purchase Summary</h6>
                    <p class="text-muted small mb-0">Detailed breakdown of all purchases by product</p>
                </div>
            </div>
            
            <div class="col-md-4">
                <div class="report-card" onclick="selectReport('supplier_performance')">
                    <div class="report-icon text-success">
                        <i class="bi bi-people"></i>
                    </div>
                    <h6>Supplier Performance</h6>
                    <p class="text-muted small mb-0">Analyze supplier reliability and quality</p>
                </div>
            </div>
            
            <div class="col-md-4">
                <div class="report-card" onclick="selectReport('spending_analysis')">
                    <div class="report-icon text-info">
                        <i class="bi bi-graph-up"></i>
                    </div>
                    <h6>Spending Analysis</h6>
                    <p class="text-muted small mb-0">Monthly spending trends by category</p>
                </div>
            </div>
            
            <div class="col-md-4">
                <div class="report-card" onclick="selectReport('order_status')">
                    <div class="report-icon text-warning">
                        <i class="bi bi-clipboard-data"></i>
                    </div>
                    <h6>Order Status Report</h6>
                    <p class="text-muted small mb-0">Summary of orders by status</p>
                </div>
            </div>
            
            <div class="col-md-4">
                <div class="report-card" onclick="selectReport('price_trends')">
                    <div class="report-icon text-danger">
                        <i class="bi bi-graph-down"></i>
                    </div>
                    <h6>Price Trends</h6>
                    <p class="text-muted small mb-0">Track price changes over time</p>
                </div>
            </div>
            
            <div class="col-md-4">
                <div class="report-card" onclick="selectReport('custom')">
                    <div class="report-icon text-secondary">
                        <i class="bi bi-sliders"></i>
                    </div>
                    <h6>Custom Report</h6>
                    <p class="text-muted small mb-0">Build your own custom report</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Report Generation Form -->
<div class="card shadow-sm mb-4">
    <div class="card-header bg-white py-3">
        <h5 class="mb-0"><i class="bi bi-funnel me-2"></i>Report Parameters</h5>
    </div>
    <div class="card-body">
        <form method="POST" id="reportForm">
            <input type="hidden" name="action" value="generate_report">
            <input type="hidden" name="report_type" id="reportType">
            
            <div class="row g-3">
                <div class="col-md-4">
                    <label class="form-label">From Date <span class="text-danger">*</span></label>
                    <input type="date" name="from_date" class="form-control" 
                           value="<?php echo date('Y-m-01'); ?>" required>
                </div>
                
                <div class="col-md-4">
                    <label class="form-label">To Date <span class="text-danger">*</span></label>
                    <input type="date" name="to_date" class="form-control" 
                           value="<?php echo date('Y-m-d'); ?>" required>
                </div>
                
                <div class="col-md-4">
                    <label class="form-label">&nbsp;</label>
                    <button type="submit" class="btn btn-primary w-100" id="generateBtn" disabled>
                        <i class="bi bi-file-earmark-bar-graph me-2"></i>Generate Report
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Report Results -->
<?php if ($reportData !== null): ?>
<div class="card shadow-sm">
    <div class="card-header bg-white py-3">
        <div class="row align-items-center">
            <div class="col">
                <h5 class="mb-0">
                    <i class="bi bi-table me-2"></i>
                    <?php echo ucwords(str_replace('_', ' ', $reportType)); ?>
                </h5>
            </div>
            <div class="col-auto">
                <div class="btn-group">
                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="printReport()">
                        <i class="bi bi-printer me-1"></i>Print
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-success" onclick="exportReport('csv')">
                        <i class="bi bi-file-earmark-spreadsheet me-1"></i>Export CSV
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="exportReport('pdf')">
                        <i class="bi bi-file-earmark-pdf me-1"></i>Export PDF
                    </button>
                </div>
            </div>
        </div>
    </div>
    <div class="card-body">
        <?php if (empty($reportData)): ?>
            <div class="text-center py-5">
                <i class="bi bi-inbox" style="font-size: 4rem; color: #d1d5db;"></i>
                <h5 class="mt-3 text-muted">No data found</h5>
                <p class="text-muted">Try adjusting your date range</p>
            </div>
        <?php else: ?>
            <div class="table-responsive" id="reportTable">
                <table class="table table-hover table-sm">
                    <thead class="table-light">
                        <tr>
                            <?php foreach (array_keys($reportData[0]) as $header): ?>
                            <th><?php echo ucwords(str_replace('_', ' ', $header)); ?></th>
                            <?php endforeach; ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($reportData as $row): ?>
                        <tr>
                            <?php foreach ($row as $key => $value): ?>
                            <td>
                                <?php
                                if (strpos($key, 'price') !== false || strpos($key, 'amount') !== false || strpos($key, 'value') !== false) {
                                    echo formatCurrency($value);
                                } elseif (strpos($key, 'date') !== false) {
                                    echo $value ? date('M j, Y', strtotime($value)) : 'N/A';
                                } elseif (strpos($key, 'rate') !== false) {
                                    echo number_format($value, 2) . '%';
                                } elseif (is_numeric($value) && $value == (int)$value) {
                                    echo number_format($value);
                                } elseif (is_numeric($value)) {
                                    echo number_format($value, 2);
                                } else {
                                    echo htmlspecialchars($value);
                                }
                                ?>
                            </td>
                            <?php endforeach; ?>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            
            <!-- Summary Statistics -->
            <div class="mt-4 p-3 bg-light rounded">
                <div class="row text-center">
                    <div class="col-md-3">
                        <h6 class="text-muted mb-1">Total Records</h6>
                        <h4 class="mb-0"><?php echo number_format(count($reportData)); ?></h4>
                    </div>
                    <?php if ($reportType === 'purchase_summary'): ?>
                    <div class="col-md-3">
                        <h6 class="text-muted mb-1">Total Orders</h6>
                        <h4 class="mb-0"><?php echo number_format(array_sum(array_column($reportData, 'order_count'))); ?></h4>
                    </div>
                    <div class="col-md-3">
                        <h6 class="text-muted mb-1">Total Spent</h6>
                        <h4 class="mb-0 text-success"><?php echo formatCurrency(array_sum(array_column($reportData, 'total_spent'))); ?></h4>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<script>
let selectedReportType = null;

function selectReport(type) {
    selectedReportType = type;
    
    // Remove active class from all cards
    document.querySelectorAll('.report-card').forEach(card => {
        card.classList.remove('active');
    });
    
    // Add active class to selected card
    event.currentTarget.classList.add('active');
    
    // Update hidden input and enable button
    document.getElementById('reportType').value = type;
    document.getElementById('generateBtn').disabled = false;
}

function printReport() {
    window.print();
}

function exportReport(format) {
    const form = document.getElementById('reportForm');
    const fromDate = form.querySelector('[name="from_date"]').value;
    const toDate = form.querySelector('[name="to_date"]').value;
    
    if (format === 'csv') {
        window.location.href = `<?php echo APP_URL; ?>/buyer/reports.php?export=csv&type=${selectedReportType}&from=${fromDate}&to=${toDate}`;
    } else if (format === 'pdf') {
        showToast('PDF export coming soon', 'info');
    }
}

// Print styling
window.addEventListener('beforeprint', function() {
    document.querySelectorAll('.btn, .sidebar, .topbar, .card-header .btn-group').forEach(el => {
        el.style.display = 'none';
    });
});

window.addEventListener('afterprint', function() {
    document.querySelectorAll('.btn, .sidebar, .topbar, .card-header .btn-group').forEach(el => {
        el.style.display = '';
    });
});
</script>

<?php renderBuyerFooter(); ?>