<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\StreamedResponse;

class LoyaltyReportController extends Controller
{
    public function index(Request $request)
    {
        $partners = DB::table('partners')->select('id', 'name')->get();
        $cards = DB::table('cards')->select('id', 'title', 'name')->get();
        $members = DB::table('members')->select('id', 'name', 'email')->get();

        $query = DB::table('transactions as t')
            ->leftJoin('members as m', 't.member_id', '=', 'm.id')
            ->leftJoin('cards as c', 't.card_id', '=', 'c.id')
            ->select(
                't.id',
                't.card_id',
                'c.title as card_title',
                'c.name as card_raw_name',
                'm.name as member_name',
                'm.email as member_email',
                't.partner_name',
                't.event',
                't.purchase_amount',
                't.points',
                't.points_used',
                't.created_at'
            );

        if ($request->filled('card_id')) {
            $query->where('t.card_id', $request->card_id);
        }

        if ($request->filled('partner_id')) {
            $query->where('t.created_by', $request->partner_id);
        }

        if ($request->filled('member_id')) {
            $query->where('t.member_id', $request->member_id);
        }

        if ($request->filled('from_date')) {
            $query->whereDate('t.created_at', '>=', $request->from_date);
        }

        if ($request->filled('to_date')) {
            $query->whereDate('t.created_at', '<=', $request->to_date);
        }

        $query->orderBy('t.created_at', 'desc');

        // 🔥 ميزة التصدير لملف إكسيل / CSV بنفس الفلاتر المحددة
        if ($request->input('action') === 'export') {
            return $this->exportToCsv($query);
        }

        $transactions = $query->get();

        return view('admin.reports.loyalty_report', compact('partners', 'cards', 'members', 'transactions'));
    }

    private function exportToCsv($query)
    {
        $response = new StreamedResponse(function () use ($query) {
            $handle = fopen('php://output', 'w');
            
            // إضافة الـ BOM لدعم اللغة العربية داخل الإكسيل بدون رموز غريبة
            fprintf($handle, chr(0xEF).chr(0xBB).chr(0xBF));

            // عناوين الأعمدة في ملف الإكسيل
            fputcsv($handle, [
                'Transaction ID',
                'Customer Name',
                'Customer Email',
                'Card Name',
                'Card ID',
                'Partner Name',
                'Event Type',
                'Purchase Amount (EGP)',
                'Points Earned',
                'Points Used',
                'Date & Time'
            ]);

            // جلب البيانات على دفعات للحفاظ على الذاكرة (Chunking)
            $query->chunk(500, function ($rows) use ($handle) {
                foreach ($rows as $row) {
                    // تحديد اسم الكارت بناءً على وجود ترجمة أو حذفه
                    $cardName = 'Deleted Card';
                    if ($row->card_title && str_contains($row->card_title, '{')) {
                        $decoded = json_decode($row->card_title);
                        $cardName = $decoded->en ?? $decoded->ar ?? $row->card_raw_name ?? 'Unnamed Card';
                    } elseif ($row->card_raw_name) {
                        $cardName = $row->card_raw_name;
                    }

                    fputcsv($handle, [
                        $row->id,
                        $row->member_name ?? 'System Guest',
                        $row->member_email ?? 'N/A',
                        $cardName,
                        $row->card_id,
                        $row->partner_name ?? 'System Admin',
                        ucfirst(str_replace('_', ' ', $row->event)),
                        $row->purchase_amount ?? 0,
                        $row->points ?? 0,
                        $row->points_used ?? 0,
                        $row->created_at
                    ]);
                }
            });

            fclose($handle);
        });

        $fileName = 'loyalty_report_' . date('Y-m-d_H-i-s') . '.csv';

        $response->headers->set('Content-Type', 'text/csv; charset=utf-8');
        $response->headers->set('Content-Disposition', 'attachment; filename="' . $fileName . '"');
        $response->headers->set('Cache-Control', 'max-age=0');

        return $response;
    }
}