<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ClassRegistration;
use App\Models\MemberRegistration;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ReportController extends Controller
{
    /**
     * Display the main reports page
     */
    public function index()
    {
        return view('admin.pages.reports');
    }

    /**
     * Get member registration data for DataTables
     */
    public function membersData(Request $request)
    {
        $query = MemberRegistration::query()
            ->select([
                'id',
                'full_name',
                'email',
                'phone',
                'membership_plan',
                'membership_price',
                'payment_method',
                'address',
                'membership_id',
                'created_at',
                DB::raw("'member' as type")
            ]);

        // Apply date range filter
        if ($request->start_date) {
            $query->whereDate('created_at', '>=', $request->start_date);
        }
        if ($request->end_date) {
            $query->whereDate('created_at', '<=', $request->end_date);
        }

        return datatables()->of($query)
            ->editColumn('created_at', function($registration) {
                return $registration->created_at->format('Y-m-d H:i:s');
            })
            ->editColumn('membership_price', function($registration) {
                return '$' . number_format($registration->membership_price, 2);
            })
            ->editColumn('payment_method', function($registration) {
                return ucwords(str_replace('_', ' ', $registration->payment_method));
            })
            ->addColumn('actions', function($registration) {
                return '<button class="btn btn-sm btn-info view-btn" data-id="'.$registration->id.'" data-type="member">
                            <i class="fas fa-eye"></i>
                        </button>';
            })
            ->toJson();
    }

    /**
     * Get class registration data for DataTables
     */
    public function classesData(Request $request)
    {
        $query = ClassRegistration::query()
            ->select([
                'id',
                'full_name',
                'email',
                'phone',
                'class_name',
                'class_schedule',
                'membership_status',
                'created_at',
                DB::raw("'class' as type")
            ]);

        // Apply date range filter
        if ($request->start_date) {
            $query->whereDate('created_at', '>=', $request->start_date);
        }
        if ($request->end_date) {
            $query->whereDate('created_at', '<=', $request->end_date);
        }

        return datatables()->of($query)
            ->editColumn('created_at', function($registration) {
                return $registration->created_at->format('Y-m-d H:i:s');
            })
            ->editColumn('membership_status', function($registration) {
                return ucwords(str_replace('-', ' ', $registration->membership_status));
            })
            ->addColumn('actions', function($registration) {
                return '<button class="btn btn-sm btn-info view-btn" data-id="'.$registration->id.'" data-type="class">
                            <i class="fas fa-eye"></i>
                        </button>';
            })
            ->toJson();
    }

    /**
     * Get chart data for registration reports
     */
    public function registrationCharts(Request $request)
    {
        // Get counts for pie chart
        $memberCount = MemberRegistration::when($request->start_date, function($query, $start_date) {
                return $query->whereDate('created_at', '>=', $start_date);
            })
            ->when($request->end_date, function($query, $end_date) {
                return $query->whereDate('created_at', '<=', $end_date);
            })
            ->count();

        $classCount = ClassRegistration::when($request->start_date, function($query, $start_date) {
                return $query->whereDate('created_at', '>=', $start_date);
            })
            ->when($request->end_date, function($query, $end_date) {
                return $query->whereDate('created_at', '<=', $end_date);
            })
            ->count();

        // Get daily registration data
        $dailyData = $this->getDailyRegistrationData($request);

        return response()->json([
            'member_count' => $memberCount,
            'class_count' => $classCount,
            'daily_labels' => $dailyData['labels'],
            'daily_members' => $dailyData['members'],
            'daily_classes' => $dailyData['classes']
        ]);
    }

    /**
     * Show details of a specific registration
     */
public function showRegistration($id, Request $request)
{
    $request->validate(['type' => 'required|in:member,class']);
    
    try {
        $model = $request->type === 'member' 
            ? MemberRegistration::findOrFail($id)
            : ClassRegistration::findOrFail($id);
            
        return response()->json([
            'success' => true,
            'data' => $this->formatRegistrationDetails($model)
        ]);
    } catch (ModelNotFoundException $e) {
        return response()->json([
            'success' => false,
            'message' => 'Registration not found'
        ], 404);
    }
}
    /**
     * Format registration details for display
     */
    private function formatRegistrationDetails($registration)
    {
        $html = '<div class="row">';
        
        if ($registration->type === 'member') {
            $html .= '
                <div class="col-md-6">
                    <h5 class="mb-3">Basic Information</h5>
                    <table class="table table-bordered">
                        <tr><th width="30%">Registration Type</th><td>Member Registration</td></tr>
                        <tr><th>Full Name</th><td>'.$registration->full_name.'</td></tr>
                        <tr><th>Email</th><td>'.$registration->email.'</td></tr>
                        <tr><th>Phone</th><td>'.$registration->phone.'</td></tr>
                        <tr><th>Registration Date</th><td>'.$registration->created_at->format('Y-m-d H:i:s').'</td></tr>
                    </table>
                </div>
                <div class="col-md-6">
                    <h5 class="mb-3">Membership Details</h5>
                    <table class="table table-bordered">
                        <tr><th width="30%">Membership ID</th><td>'.$registration->membership_id.'</td></tr>
                        <tr><th>Membership Plan</th><td>'.ucfirst($registration->membership_plan).'</td></tr>
                        <tr><th>Membership Price</th><td>$'.number_format($registration->membership_price, 2).'</td></tr>
                        <tr><th>Payment Method</th><td>'.ucwords(str_replace('_', ' ', $registration->payment_method)).'</td></tr>
                        <tr><th>Address</th><td>'.$registration->address.'</td></tr>
                    </table>
                </div>';
        } else {
            $html .= '
                <div class="col-md-6">
                    <h5 class="mb-3">Basic Information</h5>
                    <table class="table table-bordered">
                        <tr><th width="30%">Registration Type</th><td>Class Registration</td></tr>
                        <tr><th>Full Name</th><td>'.$registration->full_name.'</td></tr>
                        <tr><th>Email</th><td>'.$registration->email.'</td></tr>
                        <tr><th>Phone</th><td>'.$registration->phone.'</td></tr>
                        <tr><th>Registration Date</th><td>'.$registration->created_at->format('Y-m-d H:i:s').'</td></tr>
                    </table>
                </div>
                <div class="col-md-6">
                    <h5 class="mb-3">Class Details</h5>
                    <table class="table table-bordered">
                        <tr><th width="30%">Class Name</th><td>'.$registration->class_name.'</td></tr>
                        <tr><th>Class Schedule</th><td>'.$registration->class_schedule.'</td></tr>
                        <tr><th>Membership Status</th><td>'.ucwords(str_replace('-', ' ', $registration->membership_status)).'</td></tr>
                    </table>
                </div>';
        }

        $html .= '</div>';
        return $html;
    }

    /**
     * Get daily registration data for charts
     */
    private function getDailyRegistrationData(Request $request)
    {
        $startDate = $request->start_date ?: now()->subDays(30)->format('Y-m-d');
        $endDate = $request->end_date ?: now()->format('Y-m-d');

        // Get all dates in range
        $dates = [];
        $currentDate = $startDate;
        while ($currentDate <= $endDate) {
            $dates[] = $currentDate;
            $currentDate = date('Y-m-d', strtotime($currentDate . ' +1 day'));
        }

        // Get member registrations
        $dailyMembers = MemberRegistration::select(
                DB::raw('DATE(created_at) as date'),
                DB::raw('COUNT(*) as count')
            )
            ->whereDate('created_at', '>=', $startDate)
            ->whereDate('created_at', '<=', $endDate)
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        // Get class registrations
        $dailyClasses = ClassRegistration::select(
                DB::raw('DATE(created_at) as date'),
                DB::raw('COUNT(*) as count')
            )
            ->whereDate('created_at', '>=', $startDate)
            ->whereDate('created_at', '<=', $endDate)
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        // Prepare data for chart
        $labels = array_map(fn($date) => date('M j', strtotime($date)), $dates);
        $membersData = array_fill(0, count($dates), 0);
        $classesData = array_fill(0, count($dates), 0);

        $this->fillChartData($dailyMembers, $dates, $membersData);
        $this->fillChartData($dailyClasses, $dates, $classesData);

        return [
            'labels' => $labels,
            'members' => $membersData,
            'classes' => $classesData
        ];
    }

    /**
     * Fill chart data arrays
     */
    private function fillChartData($data, $dates, &$targetArray)
    {
        foreach ($data as $item) {
            $index = array_search($item->date, $dates);
            if ($index !== false) {
                $targetArray[$index] = $item->count;
            }
        }
    }
    public function membersVisualization(Request $request)
{
    $data = MemberRegistration::select('membership_plan', DB::raw('COUNT(*) as count'))
        ->when($request->start_date, function($query, $start_date) {
            return $query->whereDate('created_at', '>=', $start_date);
        })
        ->when($request->end_date, function($query, $end_date) {
            return $query->whereDate('created_at', '<=', $end_date);
        })
        ->groupBy('membership_plan')
        ->get();

    return response()->json([
        'labels' => $data->pluck('membership_plan')->map(function($plan) {
            return ucfirst($plan);
        }),
        'values' => $data->pluck('count')
    ]);
}
public function classesVisualization(Request $request)
{
    $data = ClassRegistration::select('class_name', DB::raw('COUNT(*) as count'))
        ->when($request->start_date, function($query, $start_date) {
            return $query->whereDate('created_at', '>=', $start_date);
        })
        ->when($request->end_date, function($query, $end_date) {
            return $query->whereDate('created_at', '<=', $end_date);
        })
        ->groupBy('class_name')
        ->get();

    return response()->json([
        'labels' => $data->pluck('class_name'),
        'values' => $data->pluck('count')
    ]);
}
}