<?php
require 'auth_check.php';
require '../config/db.php';

// --- HANDLE EXPORT LOGIC ---
if (isset($_POST['export_type'])) {
    $type = $_POST['export_type'];
    $filename = $type . "_" . date('Y-m-d') . ".csv";
    
    // Set Headers to force download
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    
    $output = fopen('php://output', 'w');

    // 1. EXPORT ORDERS
    if ($type == 'orders') {
        $start = $_POST['start_date'] . " 00:00:00";
        $end = $_POST['end_date'] . " 23:59:59";
        
        // Column Headings
        fputcsv($output, ['Order ID', 'Customer Name', 'Email', 'Phone', 'Total Amount', 'Status', 'Payment Method', 'Date']);
        
        $stmt = $pdo->prepare("
            SELECT o.id, u.name, u.email, u.phone, o.total_amount, o.status, o.payment_method, o.created_at 
            FROM orders o 
            JOIN users u ON o.user_id = u.id 
            WHERE o.created_at BETWEEN ? AND ? 
            ORDER BY o.id DESC
        ");
        $stmt->execute([$start, $end]);
        
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            fputcsv($output, $row);
        }
    }

    // 2. EXPORT CUSTOMERS
    if ($type == 'customers') {
        fputcsv($output, ['User ID', 'Name', 'Email', 'Phone', 'Wallet Balance', 'Joined Date']);
        
        $stmt = $pdo->query("SELECT id, name, email, phone, wallet_balance, created_at FROM users ORDER BY id DESC");
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            fputcsv($output, $row);
        }
    }

    // 3. EXPORT UNSOLD KEYS (BACKUP)
    if ($type == 'keys') {
        fputcsv($output, ['Key ID', 'Product Name', 'License Key', 'Status']);
        
        $stmt = $pdo->query("
            SELECT k.id, p.name, k.license_key, k.status 
            FROM license_keys k 
            JOIN products p ON k.product_id = p.id 
            WHERE k.status = 'available'
        ");
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            fputcsv($output, $row);
        }
    }

    fclose($output);
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Reports & Export</title>
    <link rel="stylesheet" href="admin_style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .report-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-top: 20px; }
        .report-card { background: white; padding: 25px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); border-top: 4px solid #3498db; }
        .form-group { margin-bottom: 15px; }
        .form-group label { font-weight: bold; display: block; margin-bottom: 5px; }
        .form-control { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
        .btn-export { background: #27ae60; color: white; border: none; padding: 12px; width: 100%; font-size: 16px; cursor: pointer; border-radius: 4px; }
        .btn-export:hover { background: #219150; }
    </style>
</head>
<body>

    <div class="sidebar">
        <?php include 'sidebar.php'; ?>
    </div>

    <div class="content">
        <h1>Data Reports & Export</h1>
        <p style="color: #666;">Download your business data for accounting and backup.</p>

        <div class="report-grid">
            
            <div class="report-card" style="border-color: #3498db;">
                <h3><i class="fas fa-file-invoice-dollar"></i> Sales Report</h3>
                <form method="POST">
                    <input type="hidden" name="export_type" value="orders">
                    
                    <div class="form-group">
                        <label>Start Date</label>
                        <input type="date" name="start_date" class="form-control" required value="<?php echo date('Y-m-01'); ?>">
                    </div>
                    <div class="form-group">
                        <label>End Date</label>
                        <input type="date" name="end_date" class="form-control" required value="<?php echo date('Y-m-d'); ?>">
                    </div>
                    
                    <button type="submit" class="btn-export" style="background: #3498db;">
                        <i class="fas fa-download"></i> Download Sales CSV
                    </button>
                </form>
            </div>

            <div class="report-card" style="border-color: #e67e22;">
                <h3><i class="fas fa-users"></i> Customer List</h3>
                <p style="margin-bottom: 20px; color: #666;">Download email list of all registered users for marketing.</p>
                <form method="POST">
                    <input type="hidden" name="export_type" value="customers">
                    <button type="submit" class="btn-export" style="background: #e67e22;">
                        <i class="fas fa-download"></i> Export Customers
                    </button>
                </form>
            </div>

            <div class="report-card" style="border-color: #e74c3c;">
                <h3><i class="fas fa-key"></i> Inventory Backup</h3>
                <p style="margin-bottom: 20px; color: #666;">Download all <strong>Available</strong> license keys as a backup file.</p>
                <form method="POST">
                    <input type="hidden" name="export_type" value="keys">
                    <button type="submit" class="btn-export" style="background: #e74c3c;">
                        <i class="fas fa-download"></i> Backup Keys
                    </button>
                </form>
            </div>

        </div>
    </div>

</body>
</html>