<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\MontessoriMembershipApplication;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
use Illuminate\Pagination\LengthAwarePaginator;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\MontessoriMembershipApplicationsExport;

class MontessoriMembershipApplicationsController extends Controller
{
    public function index(Request $request)
    {
        $this->authorize('admin_additional_pages');

        // Check if table exists using multiple methods
        $tableExists = false;
        try {
            $tableExists = Schema::hasTable('montessori_membership_applications');
        } catch (\Exception $e) {
            // If Schema fails, try DB query
            try {
                $result = DB::select("SHOW TABLES LIKE 'montessori_membership_applications'");
                $tableExists = !empty($result);
            } catch (\Exception $e2) {
                // Last resort: try to query the table
                try {
                    DB::table('montessori_membership_applications')->limit(1)->get();
                    $tableExists = true;
                } catch (\Exception $e3) {
                    $tableExists = false;
                }
            }
        }
        
        if (!$tableExists) {
            // Create empty paginator
            $emptyCollection = collect([]);
            $perPage = 20;
            $currentPage = LengthAwarePaginator::resolveCurrentPage();
            $emptyPaginator = new LengthAwarePaginator(
                $emptyCollection,
                $emptyCollection->count(),
                $perPage,
                $currentPage,
                ['path' => request()->url(), 'query' => request()->query()]
            );
            
            return view('admin.montessori_membership_applications.index', [
                'pageTitle' => 'طلبات عضوية المونتيسوري',
                'applications' => $emptyPaginator,
                'totalApplications' => 0,
                'pendingApplications' => 0,
                'approvedApplications' => 0,
                'rejectedApplications' => 0,
                'tableMissing' => true,
            ]);
        }

        try {
            $query = MontessoriMembershipApplication::query();

            // Filter by status
            if ($request->has('status') && !empty($request->status)) {
                $query->where('status', $request->status);
            }

            // Search
            if ($request->has('search') && !empty($request->search)) {
                $search = $request->search;
                $query->where(function($q) use ($search) {
                    $q->whereRaw("JSON_UNQUOTE(JSON_EXTRACT(form_data, '$.name')) LIKE ?", ["%{$search}%"])
                      ->orWhereRaw("JSON_UNQUOTE(JSON_EXTRACT(form_data, '$.email')) LIKE ?", ["%{$search}%"])
                      ->orWhereRaw("JSON_UNQUOTE(JSON_EXTRACT(form_data, '$.phone')) LIKE ?", ["%{$search}%"]);
                });
            }

            $applications = $query->orderBy('created_at', 'desc')->paginate(20);
        } catch (\Exception $e) {
            // If query fails, return empty paginator
            $emptyCollection = collect([]);
            $perPage = 20;
            $currentPage = LengthAwarePaginator::resolveCurrentPage();
            $applications = new LengthAwarePaginator(
                $emptyCollection,
                $emptyCollection->count(),
                $perPage,
                $currentPage,
                ['path' => request()->url(), 'query' => request()->query()]
            );
        }

        // Statistics
        try {
            $totalApplications = MontessoriMembershipApplication::count();
            $pendingApplications = MontessoriMembershipApplication::where('status', 'pending')->count();
            $approvedApplications = MontessoriMembershipApplication::where('status', 'approved')->count();
            $rejectedApplications = MontessoriMembershipApplication::where('status', 'rejected')->count();
        } catch (\Exception $e) {
            $totalApplications = 0;
            $pendingApplications = 0;
            $approvedApplications = 0;
            $rejectedApplications = 0;
        }

        $data = [
            'pageTitle' => 'طلبات عضوية المونتيسوري',
            'applications' => $applications,
            'totalApplications' => $totalApplications,
            'pendingApplications' => $pendingApplications,
            'approvedApplications' => $approvedApplications,
            'rejectedApplications' => $rejectedApplications,
        ];

        return view('admin.montessori_membership_applications.index', $data);
    }

    public function show($id)
    {
        $this->authorize('admin_additional_pages');

        $application = MontessoriMembershipApplication::findOrFail($id);

        $data = [
            'pageTitle' => 'تفاصيل طلب العضوية',
            'application' => $application,
        ];

        return view('admin.montessori_membership_applications.show', $data);
    }

    public function updateStatus(Request $request, $id)
    {
        $this->authorize('admin_additional_pages');

        $this->validate($request, [
            'status' => 'required|in:pending,approved,rejected'
        ]);

        $application = MontessoriMembershipApplication::findOrFail($id);
        $application->update(['status' => $request->status]);

        return back()->with(['msg' => 'تم تحديث الحالة بنجاح']);
    }

    public function delete($id)
    {
        $this->authorize('admin_additional_pages');

        $application = MontessoriMembershipApplication::findOrFail($id);
        $application->delete();

        return back()->with(['msg' => 'تم الحذف بنجاح']);
    }

    public function exportExcel(Request $request)
    {
        $this->authorize('admin_additional_pages');

        // Check if table exists
        if (!Schema::hasTable('montessori_membership_applications')) {
            return back()->with(['msg' => 'الجدول غير موجود. لا يمكن التصدير.']);
        }

        try {
            $query = MontessoriMembershipApplication::query();

            // Apply same filters as index
            if ($request->has('status') && !empty($request->status)) {
                $query->where('status', $request->status);
            }

            if ($request->has('search') && !empty($request->search)) {
                $search = $request->search;
                $query->where(function($q) use ($search) {
                    $q->whereRaw("JSON_UNQUOTE(JSON_EXTRACT(form_data, '$.name')) LIKE ?", ["%{$search}%"])
                      ->orWhereRaw("JSON_UNQUOTE(JSON_EXTRACT(form_data, '$.email')) LIKE ?", ["%{$search}%"])
                      ->orWhereRaw("JSON_UNQUOTE(JSON_EXTRACT(form_data, '$.phone')) LIKE ?", ["%{$search}%"]);
                });
            }

            $applications = $query->orderBy('created_at', 'desc')->get();

            $export = new MontessoriMembershipApplicationsExport($applications);

            return Excel::download($export, 'montessori_membership_applications.xlsx');

        } catch (\Exception $e) {
            return back()->with(['msg' => 'حدث خطأ أثناء التصدير: ' . $e->getMessage()]);
        }
    }
}
