<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\DiplomaProgramCounter;
use App\Models\Webinar;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

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

        $query = DiplomaProgramCounter::with('webinar');

        if (!empty($request->get('webinar_id'))) {
            $query->where('webinar_id', $request->get('webinar_id'));
        }

        $counters = $query->orderBy('created_at', 'desc')->paginate(10);

        $data = [
            'pageTitle' => 'إعدادات عداد برامج الدبلوم',
            'counters' => $counters,
            'webinar_id' => $request->get('webinar_id'),
        ];

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

    public function create()
    {
        $this->authorize('admin_certificate_template_create');

        $webinars = Webinar::where('status', Webinar::$active)
            ->orderBy('created_at', 'desc')
            ->get();

        $data = [
            'pageTitle' => 'إنشاء عداد برنامج دبلوم',
            'webinars' => $webinars,
        ];

        return view('admin.diploma_counters.create', $data);
    }

    public function store(Request $request)
    {
        $this->authorize('admin_certificate_template_create');

        $rules = [
            'webinar_id' => 'required|exists:webinars,id',
            'orders_count' => 'nullable|integer|min:0',
            'total_sales' => 'nullable|numeric|min:0',
            'products_count' => 'nullable|integer|min:0',
            'completion_rate' => 'nullable|integer|min:0|max:100',
            'participants_count' => 'nullable|integer|min:0',
            'is_active' => 'nullable|boolean',
        ];

        $this->validate($request, $rules);

        $data = $request->all();

        DiplomaProgramCounter::create([
            'webinar_id' => $data['webinar_id'],
            'orders_count' => $data['orders_count'] ?? 0,
            'total_sales' => $data['total_sales'] ?? 0,
            'products_count' => $data['products_count'] ?? 0,
            'completion_rate' => $data['completion_rate'] ?? 0,
            'participants_count' => $data['participants_count'] ?? 0,
            'is_active' => isset($data['is_active']) ? (bool)$data['is_active'] : true,
            'created_at' => time(),
            'updated_at' => time(),
        ]);

        return redirect('/admin/diploma-counters')->with(['success' => 'تم الإنشاء بنجاح']);
    }

    public function edit($id)
    {
        $this->authorize('admin_certificate_template_edit');

        $counter = DiplomaProgramCounter::findOrFail($id);
        $webinars = Webinar::where('status', Webinar::$active)
            ->orderBy('created_at', 'desc')
            ->get();

        $data = [
            'pageTitle' => 'تعديل عداد برنامج دبلوم',
            'counter' => $counter,
            'webinars' => $webinars,
        ];

        return view('admin.diploma_counters.edit', $data);
    }

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

        $rules = [
            'webinar_id' => 'required|exists:webinars,id',
            'orders_count' => 'nullable|integer|min:0',
            'total_sales' => 'nullable|numeric|min:0',
            'products_count' => 'nullable|integer|min:0',
            'completion_rate' => 'nullable|integer|min:0|max:100',
            'participants_count' => 'nullable|integer|min:0',
            'is_active' => 'nullable|boolean',
        ];

        $this->validate($request, $rules);

        $counter = DiplomaProgramCounter::findOrFail($id);
        $data = $request->all();

        $counter->update([
            'webinar_id' => $data['webinar_id'],
            'orders_count' => $data['orders_count'] ?? 0,
            'total_sales' => $data['total_sales'] ?? 0,
            'products_count' => $data['products_count'] ?? 0,
            'completion_rate' => $data['completion_rate'] ?? 0,
            'participants_count' => $data['participants_count'] ?? 0,
            'is_active' => isset($data['is_active']) ? (bool)$data['is_active'] : true,
            'updated_at' => time(),
        ]);

        return redirect('/admin/diploma-counters')->with(['success' => 'تم التعديل بنجاح']);
    }

    public function destroy(Request $request, $id)
    {
        Log::info('DiplomaCounter Delete - Start', [
            'counter_id' => $id,
            'request_all' => $request->all(),
            'request_headers' => $request->headers->all(),
            'user_id' => auth()->id(),
            'user_email' => auth()->user()->email ?? 'N/A',
            'request_method' => request()->method(),
            'request_url' => request()->fullUrl(),
            'ip' => $request->ip(),
        ]);

        try {
            // Check authorization
            try {
                $this->authorize('admin_certificate_template_delete');
                Log::info('DiplomaCounter Delete - Authorization passed');
            } catch (\Exception $e) {
                Log::error('DiplomaCounter Delete - Authorization failed', [
                    'error' => $e->getMessage(),
                    'counter_id' => $id,
                ]);
                return response()->json([
                    'code' => 403,
                    'title' => trans('admin/main.error'),
                    'text' => 'ليس لديك صلاحية للحذف',
                ], 403);
            }

            // Find counter
            $counter = DiplomaProgramCounter::find($id);
            
            if (!$counter) {
                Log::warning('DiplomaCounter Delete - Counter not found', [
                    'counter_id' => $id,
                ]);
                return response()->json([
                    'code' => 404,
                    'title' => trans('admin/main.error'),
                    'text' => 'العداد غير موجود',
                ], 404);
            }

            Log::info('DiplomaCounter Delete - Counter found', [
                'counter_id' => $counter->id,
                'webinar_id' => $counter->webinar_id,
            ]);

            // Delete counter
            $deleted = $counter->delete();

            if ($deleted) {
                Log::info('DiplomaCounter Delete - Success', [
                    'counter_id' => $id,
                ]);

                return response()->json([
                    'code' => 200,
                    'title' => trans('admin/main.success'),
                    'text' => 'تم الحذف بنجاح',
                ]);
            } else {
                Log::error('DiplomaCounter Delete - Delete failed', [
                    'counter_id' => $id,
                ]);

                return response()->json([
                    'code' => 500,
                    'title' => trans('admin/main.error'),
                    'text' => 'فشل الحذف',
                ], 500);
            }

        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            Log::error('DiplomaCounter Delete - Model not found', [
                'counter_id' => $id,
                'error' => $e->getMessage(),
            ]);

            return response()->json([
                'code' => 404,
                'title' => trans('admin/main.error'),
                'text' => 'العداد غير موجود',
            ], 404);

        } catch (\Exception $e) {
            Log::error('DiplomaCounter Delete - Exception', [
                'counter_id' => $id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            return response()->json([
                'code' => 500,
                'title' => trans('admin/main.error'),
                'text' => 'حدث خطأ: ' . $e->getMessage(),
            ], 500);
        }
    }
}

