<?php

namespace App\Http\Controllers\SuperAdmin\Ramadan;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Carbon\Carbon;

// ✅ NEW (from LivesNewController style)
use App\Models\LiveStream;
use App\Models\User;
use App\Models\ExcusedAbsence;
use Illuminate\Validation\ValidationException;
use App\Services\SuperAdminNotificationService;

class RamadanSystemController extends Controller
{
    /* =========================
     | Core Helpers
     ========================= */

    // ✅ Timezones
    private function jordanTz(): string
    {
        return 'Asia/Amman';
    }

    private function jerusalemTz(): string
    {
        return 'Asia/Jerusalem';
    }

    private function tzNow(string $tz): Carbon
    {
        return Carbon::now($tz);
    }

    private function jordanNow(): Carbon
    {
        return $this->tzNow($this->jordanTz());
    }

    private function jerusalemNow(): Carbon
    {
        return $this->tzNow($this->jerusalemTz());
    }

    private function now(): string
    {
        return now()->toDateTimeString();
    }

    private function userDisplayName(?int $userId): string
    {
        if (!$userId || $userId <= 0) return 'غير معروف';

        $u = User::query()->where('id', $userId)->first(['name','username','email']);
        if (!$u) return "User#{$userId}";

        $name = trim((string)($u->name ?? ''));
        if ($name !== '') return $name;

        $un = trim((string)($u->username ?? ''));
        if ($un !== '') return $un;

        $em = trim((string)($u->email ?? ''));
        if ($em !== '') return $em;

        return "User#{$userId}";
    }


    /**
     * ✅ شرح عربي موسّع ومفهوم عن الحدث (بناءً على التفاصيل)
     */
    private function buildArabicNarrative(string $event, array $details, string $actorName, int $actorId): string
    {
        $parts = [];

        $targetUserId = (int)($details['assigned_user_id']
            ?? $details['target_user_id']
            ?? $details['user_id']
            ?? 0);

        $targetName = $targetUserId > 0 ? $this->userDisplayName($targetUserId) : null;

        $slotId    = $details['slot_id'] ?? $details['slotId'] ?? null;
        $slotLabel = $details['slot_label'] ?? $details['slotLabel'] ?? null;
        $sDate     = $details['slot_scheduled_date'] ?? $details['scheduled_date'] ?? $details['date'] ?? null;
        $sTime     = $details['slot_scheduled_time'] ?? $details['scheduled_time'] ?? $details['time'] ?? null;

        $liveId = $details['live_id'] ?? $details['live_stream_id'] ?? $details['liveId'] ?? null;

        $isSahra = (int)($details['is_sahra'] ?? 0) === 1;
        $topics  = (string)($details['sahra_topics'] ?? '');

        // جملة افتتاحية
        $parts[] = "تم تسجيل هذا الحدث تلقائيًا ضمن نظام رمضان.";
        $parts[] = "العملية: {$event}.";
        $parts[] = "المسؤول الذي قام بالإجراء: {$actorName} (ID: {$actorId}).";

        if ($targetUserId > 0 && $targetName) {
            $parts[] = "العضو المستهدف/المعني: {$targetName} (ID: {$targetUserId}).";
        }

        if ($slotId || $slotLabel || $sDate || $sTime) {
            $slotTxt = [];
            if ($slotLabel) $slotTxt[] = "عنوان الساعة: {$slotLabel}";
            if ($slotId)    $slotTxt[] = "Slot ID: {$slotId}";
            if ($sDate)     $slotTxt[] = "التاريخ: {$sDate}";
            if ($sTime)     $slotTxt[] = "الوقت: {$sTime}";
            $parts[] = "تفاصيل ساعة رمضان: " . implode(" — ", $slotTxt) . ".";
        }

        if ($liveId) {
            $parts[] = "تم ربط/إنشاء لايف مرتبط بهذه العملية (Live ID: {$liveId}).";
        }

        if ($isSahra) {
            $parts[] = "هذا الحدث مُصنّف كسَهرة رمضانية.";
            if ($topics !== '') {
                $parts[] = "تفاصيل/مواضيع السهرة: {$topics}.";
            }
        }

        // مسابقات/مالية/ميديا إن وجدت
        if (!empty($details['competition_id'])) {
            $parts[] = "مرجع المسابقة: Competition ID: " . $details['competition_id'] . ".";
        }
        if (!empty($details['record_id'])) {
            $parts[] = "مرجع السجل المالي: Record ID: " . $details['record_id'] . ".";
        }
        if (!empty($details['media_id'])) {
            $parts[] = "مرجع الميديا: Media ID: " . $details['media_id'] . ".";
        }
        if (!empty($details['post_id'])) {
            $parts[] = "مرجع بابا غنوج: Post ID: " . $details['post_id'] . ".";
        }

        return implode("\n", array_map(fn($x)=>"• ".$x, $parts));
    }
    /**
     * ✅ Insert row into ramadan_log_entries
     */
    private function insertRamadanLogEntry(
        int $seasonId,
        string $title,
        string $body,
        array $tags = [],
        bool $pinned = false,
        ?int $createdBy = null,
        ?string $logDate = null
    ): void {
        $tagsStr = trim(implode(',', array_values(array_filter($tags))));
        $tagsStr = Str::limit($tagsStr, 255, '');

        // created_at/updated_at نثبتها على توقيت الأردن (كما طلبت سابقاً)
        $dtJo = $this->jordanNow();
        $logDate = $logDate ?: $dtJo->toDateString();

        DB::table('ramadan_log_entries')->insert([
            'season_id'  => $seasonId,
            'log_date'   => $logDate,
            'title'      => Str::limit($title, 190, ''),
            'body'       => $body,
            'tags'       => $tagsStr !== '' ? $tagsStr : null,
            'is_pinned'  => $pinned ? 1 : 0,
            'created_by' => $createdBy ?: (auth()->id() ?? null),
            'created_at' => $dtJo->toDateTimeString(),
            'updated_at' => $dtJo->toDateTimeString(),
        ]);
    }

    /**
     * ✅ Auto Log builder:
     * - عنوان: [اوتوماتيكي] ... + توقيت الأردن وتوقيت القدس
     * - body: مرتب بأسطر عربية + تفاصيل + Request meta + JSON
     */
    private function autoLog(
        string $event,
        array $details = [],
        ?Request $request = null,
        array $tags = [],
        bool $pinned = false,
        ?int $seasonId = null,
        ?int $actorId = null
    ): void {
        $season = $this->activeSeason();
        $seasonId = $seasonId ?: (int)($season->id ?? 0);

        $actorId   = $actorId ?: (int)(auth()->id() ?? 0);
        $actorName = $this->userDisplayName($actorId);

        $dtJo  = $this->jordanNow();
        $dtJer = $this->jerusalemNow();

        $dateJo = $dtJo->toDateString();
        $timeJo = $dtJo->format('H:i');
        $dateJer = $dtJer->toDateString();
        $timeJer = $dtJer->format('H:i');

        // ✅ Title (190 char max in DB anyway)
        $title = "[اوتوماتيكي] {$event} - تمت بواسطة {$actorName} - بتاريخ {$dateJo} - وقت {$timeJo} بتوقيت الأردن | {$dateJer} {$timeJer} بتوقيت القدس";

        // ✅ Body مرتب بالعربي
        $lines = [];
        $lines[] = "[اوتوماتيكي]";
        $lines[] = "الحدث: {$event}";
        $lines[] = "تمت بواسطة: {$actorName} (ID: {$actorId})";
        $lines[] = "---------------------------------------------";
        $lines[] = "تاريخ/وقت الحدث (توقيت الأردن): {$dtJo->toDateTimeString()} ({$this->jordanTz()})";
        $lines[] = "UTC Offset (الأردن): {$dtJo->format('P')}";
        $lines[] = "تاريخ/وقت الحدث (توقيت القدس): {$dtJer->toDateTimeString()} ({$this->jerusalemTz()})";
        $lines[] = "UTC Offset (القدس): {$dtJer->format('P')}";


        $lines[] = "شرح موسّع عن الحدث:";
        $lines[] = $this->buildArabicNarrative($event, $details, $actorName, $actorId);
        $lines[] = "---------------------------------------------";

        if (!empty($details)) {
            $lines[] = "التفاصيل:";
            foreach ($details as $k => $v) {
                if (is_array($v) || is_object($v)) {
                    $v = json_encode($v, JSON_UNESCAPED_UNICODE);
                } elseif (is_bool($v)) {
                    $v = $v ? 'true' : 'false';
                } elseif ($v === null) {
                    $v = 'null';
                }
                $lines[] = "- {$k}: {$v}";
            }
        } else {
            $lines[] = "التفاصيل: لا يوجد";
        }

        if ($request) {
            $lines[] = "---------------------------------------------";
            $lines[] = "معلومات الطلب (Request):";
            $lines[] = "- method: " . $request->method();
            $lines[] = "- url: " . $request->fullUrl();
            $lines[] = "- ip: " . ($request->ip() ?: 'n/a');
            $ua = (string)$request->userAgent();
            $lines[] = "- user_agent: " . ($ua !== '' ? mb_substr($ua, 0, 255) : 'n/a');
        }

        // Raw JSON
        $lines[] = "---------------------------------------------";
        $lines[] = "JSON خام (RAW JSON):";
        $lines[] = json_encode($details, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

        $body = implode("\n", $lines);

        $tags = array_values(array_unique(array_merge(['auto','ramadan'], $tags)));

        // log_date نخليه حسب الأردن
        $this->insertRamadanLogEntry(
            $seasonId,
            $title,
            $body,
            $tags,
            $pinned,
            $actorId,
            $dateJo
        );
    }

    /**
     * ✅ Safe wrapper (حتى لو فشل اللوج ما يكسر العملية الأساسية)
     */
    private function safeAutoLog(
        string $event,
        array $details = [],
        ?Request $request = null,
        array $tags = [],
        bool $pinned = false,
        ?int $seasonId = null,
        ?int $actorId = null
    ): void {
        try {
            $this->autoLog($event, $details, $request, $tags, $pinned, $seasonId, $actorId);
        } catch (\Throwable $e) {
            try {
                \Log::error('Ramadan autoLog failed', [
                    'event' => $event,
                    'error' => $e->getMessage(),
                ]);
            } catch (\Throwable $e2) {}
        }
    }

    private function activeSeason()
    {
        $season = DB::table('ramadan_seasons')->where('is_active', 1)->orderByDesc('id')->first();

        if (!$season) {
            $id = DB::table('ramadan_seasons')->insertGetId([
                'title' => 'رمضان ' . now()->year,
                'gregorian_year' => now()->year,
                'starts_at' => now()->startOfDay()->toDateTimeString(),
                'ends_at' => now()->addDays(30)->startOfDay()->toDateTimeString(),
                'is_active' => 1,
                'created_by' => auth()->id(),
                'created_at' => now(),
                'updated_at' => now(),
            ]);
            $season = DB::table('ramadan_seasons')->where('id', $id)->first();

            // ✅ Auto log season created
            $this->safeAutoLog(
                "إنشاء موسم رمضان جديد تلقائياً",
                [
                    'season_id' => (int)$id,
                    'title' => (string)($season->title ?? ''),
                    'gregorian_year' => (int)($season->gregorian_year ?? 0),
                    'starts_at' => (string)($season->starts_at ?? ''),
                    'ends_at' => (string)($season->ends_at ?? ''),
                    'is_active' => (int)($season->is_active ?? 0),
                ],
                null,
                ['season']
            );
        }

        return $season;
    }

    private function view(string $page, array $data = [])
    {
        $season = $this->activeSeason();

        return view('superadmin.ramadan.app', array_merge($data, [
            'page' => $page,
            'season' => $season,
        ]));
    }

    private function notifySuperAdmins(string $message, ?string $actionUrl = null, string $icon = 'fa-moon')
    {
        DB::table('superadmin_notifications')->insert([
            'target_user_id' => null,
            'message' => $message,
            'users_reads' => json_encode([]),
            'type' => 'ramadan',
            'icon' => $icon,
            'action_url' => $actionUrl,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    private function createHubNotification(string $type, string $title, string $body, string $audience = 'all', ?string $url = null, ?string $sendAt = null, array $meta = [])
    {
        $id = DB::table('notification_hub_notifications')->insertGetId([
            'type' => $type,
            'ref_id' => null,
            'title' => $title,
            'body' => $body,
            'url' => $url,
            'audience' => $audience,
            'status' => $sendAt ? 'scheduled' : 'sent',
            'send_at' => $sendAt,
            'sent_at' => $sendAt ? null : now(),
            'created_by' => auth()->id(),
            'sent_by' => $sendAt ? null : auth()->id(),
            'meta_json' => $meta ? json_encode($meta, JSON_UNESCAPED_UNICODE) : null,
            'sent_count' => 0,
            'push_sent' => 0,
            'internal_sent' => 0,
            'failed_count' => 0,
            'last_error' => null,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        DB::table('notification_hub_logs')->insert([
            'notification_id' => $id,
            'channel' => 'internal',
            'status' => $sendAt ? 'queued' : 'sent',
            'error' => null,
            'created_at' => now(),
        ]);

        return $id;
    }

    private function createManualNotification(string $title, string $content, string $recipientType, array $userIds = [], array $extra = [])
    {
        $notificationId = DB::table('manual_notifications')->insertGetId([
            'title' => $title,
            'content' => $content,
            'attachment' => $extra['attachment'] ?? null,
            'attachment_type' => $extra['attachment_type'] ?? null,
            'recipient_type' => $recipientType,
            'recipient_data' => $userIds ? json_encode($userIds) : null,
            'status' => 'sent',
            'sent_at' => now(),
            'created_by' => auth()->id(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        foreach ($userIds as $uid) {
            DB::table('notification_recipients')->insert([
                'notification_id' => $notificationId,
                'user_id' => $uid,
                'read' => 0,
                'read_at' => null,
                'recipient_notes' => null,
                'last_interaction_at' => null,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }

        return $notificationId;
    }

    private function usersByAudience(string $audience): array
    {
        $q = DB::table('users')->select('id')->where('account_status', 'active');

        if ($audience === 'moderators') {
            $q->whereIn('membership_status', ['moderator', 'super-admin']);
        } elseif ($audience === 'beta') {
            $q->where('membership_status', 'beta');
        } elseif ($audience === 'male') {
            $q->where('gender', 'male');
        } elseif ($audience === 'female') {
            $q->where('gender', 'female');
        }

        return $q->pluck('id')->map(fn($v) => (int)$v)->toArray();
    }

    private function ramadanCompetitionIds(int $seasonId): array
    {
        return DB::table('ramadan_competition_links')
            ->where('season_id', $seasonId)
            ->pluck('competition_id')
            ->map(fn($v) => (int)$v)
            ->toArray();
    }

    /* =========================
     | Pages
     ========================= */
    public function index()
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $stats = [
            'participants' => (int)DB::table('ramadan_participants')->where('season_id', $seasonId)->count(),
            'competitions' => (int)DB::table('ramadan_competition_links')->where('season_id', $seasonId)->count(),
            'schedule_slots' => (int)DB::table('ramadan_schedule_slots')->where('season_id', $seasonId)->count(),
            'alerts' => (int)DB::table('ramadan_alerts')->where('season_id', $seasonId)->count(),
            'missions' => (int)DB::table('ramadan_missions')->where('season_id', $seasonId)->count(),
        ];

        return $this->view('dashboard', compact('stats'));
    }

    /* =========================
     | Competitions
     ========================= */
    public function competitionsIndex(Request $request)
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $linkedIds = $this->ramadanCompetitionIds($seasonId);

        $competitions = DB::table('competitions')
            ->whereIn('id', $linkedIds ?: [0])
            ->orderByDesc('id')
            ->get();

        $allCompetitions = DB::table('competitions')->orderByDesc('id')->limit(200)->get();

        return $this->view('competitions', compact('competitions', 'allCompetitions'));
    }

    public function competitionStore(Request $request)
    {
        $data = $request->validate([
            'title' => 'required|string|max:190',
            'description' => 'required|string',
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
            'status' => 'nullable|in:draft,active,closed,archived',
        ]);

        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $competitionId = DB::table('competitions')->insertGetId([
            'title' => $data['title'],
            'description' => $data['description'],
            'participant_types' => json_encode(['all']),
            'specific_participants' => null,
            'terms' => null,
            'start_date' => $data['start_date'],
            'end_date' => $data['end_date'],
            'has_end_date' => 1,
            'status' => $data['status'] ?? 'draft',
            'created_by' => auth()->id(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        DB::table('ramadan_competition_links')->insert([
            'season_id' => $seasonId,
            'competition_id' => $competitionId,
            'is_featured' => 0,
            'notes' => 'Created from Ramadan panel',
            'created_by' => auth()->id(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $this->notifySuperAdmins("✅ تم إنشاء مسابقة رمضانية جديدة: {$data['title']}", route('superadmin.ramadan.competitions.index'), 'fa-trophy');

        // ✅ AUTO LOG
        $this->safeAutoLog(
            "إنشاء مسابقة رمضانية جديدة",
            [
                'competition_id' => (int)$competitionId,
                'title' => $data['title'],
                'start_date' => $data['start_date'],
                'end_date' => $data['end_date'],
                'status' => $data['status'] ?? 'draft',
                'season_id' => $seasonId,
            ],
            $request,
            ['competitions','create']
        );

        return back()->with('success', 'تم إنشاء المسابقة وربطها برمضان ✅');
    }

    public function competitionLink(Request $request)
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $data = $request->validate([
            'competition_id' => 'required|integer',
        ]);

        DB::table('ramadan_competition_links')->updateOrInsert(
            ['season_id' => $seasonId, 'competition_id' => $data['competition_id']],
            ['created_by' => auth()->id(), 'created_at' => now(), 'updated_at' => now()]
        );

        $this->notifySuperAdmins("🔗 تم ربط مسابقة برمضان (ID: {$data['competition_id']})", route('superadmin.ramadan.competitions.index'), 'fa-link');

        // ✅ AUTO LOG
        $this->safeAutoLog(
            "ربط مسابقة بموسم رمضان",
            [
                'season_id' => $seasonId,
                'competition_id' => (int)$data['competition_id'],
            ],
            $request,
            ['competitions','link']
        );

        return back()->with('success', 'تم الربط ✅');
    }

    public function competitionUnlink(int $competitionId)
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        DB::table('ramadan_competition_links')
            ->where('season_id', $seasonId)
            ->where('competition_id', $competitionId)
            ->delete();

        $this->notifySuperAdmins("⛔ تم فك ربط مسابقة عن رمضان (ID: {$competitionId})", route('superadmin.ramadan.competitions.index'), 'fa-unlink');

        // ✅ AUTO LOG
        $this->safeAutoLog(
            "فك ربط مسابقة عن موسم رمضان",
            [
                'season_id' => $seasonId,
                'competition_id' => (int)$competitionId,
            ],
            request(),
            ['competitions','unlink','delete']
        );

        return back()->with('success', 'تم فك الربط ✅');
    }

    public function competitionsFinancial(Request $request)
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $linkedIds = $this->ramadanCompetitionIds($seasonId);
        $competitionId = (int)($request->query('competition_id') ?: ($linkedIds[0] ?? 0));

        $competition = $competitionId ? DB::table('competitions')->where('id', $competitionId)->first() : null;

        $prizes = DB::table('ramadan_competition_prizes')
            ->where('season_id', $seasonId)
            ->when($competitionId, fn($q) => $q->where('competition_id', $competitionId))
            ->orderByDesc('id')
            ->get();

        $records = DB::table('ramadan_competition_financial_records')
            ->where('season_id', $seasonId)
            ->when($competitionId, fn($q) => $q->where('competition_id', $competitionId))
            ->orderByDesc('id')
            ->get();

        $competitions = DB::table('competitions')->whereIn('id', $linkedIds ?: [0])->orderByDesc('id')->get();

        return $this->view('financial', compact('competitions', 'competition', 'competitionId', 'prizes', 'records'));
    }

    public function prizeStore(Request $request, int $competitionId)
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $data = $request->validate([
            'title' => 'required|string|max:190',
            'qty' => 'required|integer|min:1',
            'unit_cost' => 'nullable|numeric|min:0',
            'currency' => 'nullable|string|max:10',
            'notes' => 'nullable|string|max:500',
        ]);

        $prizeId = DB::table('ramadan_competition_prizes')->insertGetId([
            'season_id' => $seasonId,
            'competition_id' => $competitionId,
            'title' => $data['title'],
            'qty' => (int)$data['qty'],
            'unit_cost' => $data['unit_cost'],
            'currency' => $data['currency'] ?? 'ILS',
            'notes' => $data['notes'] ?? null,
            'created_by' => auth()->id(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $this->notifySuperAdmins("🎁 إضافة جائزة لمسابقات رمضان (Competition ID: {$competitionId})", route('superadmin.ramadan.competitions.financial', ['competition_id'=>$competitionId]), 'fa-gift');

        // ✅ AUTO LOG
        $this->safeAutoLog(
            "إضافة جائزة لمسابقة رمضان",
            [
                'prize_id' => (int)$prizeId,
                'season_id' => $seasonId,
                'competition_id' => (int)$competitionId,
                'title' => $data['title'],
                'qty' => (int)$data['qty'],
                'unit_cost' => $data['unit_cost'],
                'currency' => $data['currency'] ?? 'ILS',
                'notes' => $data['notes'] ?? null,
            ],
            $request,
            ['financial','prize','create']
        );

        return back()->with('success', 'تمت إضافة الجائزة ✅');
    }

    public function prizeDestroy(int $id)
    {
        $row = DB::table('ramadan_competition_prizes')->where('id', $id)->first();
        DB::table('ramadan_competition_prizes')->where('id', $id)->delete();

        // ✅ AUTO LOG
        $this->safeAutoLog(
            "حذف جائزة من مسابقات رمضان",
            [
                'prize_id' => (int)$id,
                'season_id' => (int)($row->season_id ?? 0),
                'competition_id' => (int)($row->competition_id ?? 0),
                'title' => (string)($row->title ?? ''),
                'qty' => (int)($row->qty ?? 0),
                'unit_cost' => $row->unit_cost ?? null,
                'currency' => (string)($row->currency ?? ''),
            ],
            request(),
            ['financial','prize','delete']
        );

        return back()->with('success', 'تم حذف الجائزة ✅');
    }

    public function financeStore(Request $request, int $competitionId)
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $data = $request->validate([
            'kind' => 'required|in:budget,expense,prize,sponsor,other',
            'title' => 'required|string|max:190',
            'amount' => 'required|numeric|min:0',
            'currency' => 'nullable|string|max:10',
            'vendor' => 'nullable|string|max:190',
            'paid_at' => 'nullable|date',
            'meta_json' => 'nullable|string',
        ]);

        $recId = DB::table('ramadan_competition_financial_records')->insertGetId([
            'season_id' => $seasonId,
            'competition_id' => $competitionId,
            'kind' => $data['kind'],
            'title' => $data['title'],
            'amount' => $data['amount'],
            'currency' => $data['currency'] ?? 'ILS',
            'vendor' => $data['vendor'] ?? null,
            'receipt_path' => null,
            'paid_at' => $data['paid_at'] ?? null,
            'meta_json' => $data['meta_json'] ?? null,
            'created_by' => auth()->id(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $this->notifySuperAdmins("💸 سجل مالي جديد لمسابقات رمضان (Competition ID: {$competitionId})", route('superadmin.ramadan.competitions.financial', ['competition_id'=>$competitionId]), 'fa-coins');

        // ✅ AUTO LOG
        $this->safeAutoLog(
            "إضافة سجل مالي لمسابقات رمضان",
            [
                'record_id' => (int)$recId,
                'season_id' => $seasonId,
                'competition_id' => (int)$competitionId,
                'kind' => $data['kind'],
                'title' => $data['title'],
                'amount' => $data['amount'],
                'currency' => $data['currency'] ?? 'ILS',
                'vendor' => $data['vendor'] ?? null,
                'paid_at' => $data['paid_at'] ?? null,
            ],
            $request,
            ['financial','record','create']
        );

        return back()->with('success', 'تمت إضافة السجل المالي ✅');
    }

    public function financeDestroy(int $id)
    {
        $row = DB::table('ramadan_competition_financial_records')->where('id', $id)->first();
        DB::table('ramadan_competition_financial_records')->where('id', $id)->delete();

        // ✅ AUTO LOG
        $this->safeAutoLog(
            "حذف سجل مالي لمسابقات رمضان",
            [
                'record_id' => (int)$id,
                'season_id' => (int)($row->season_id ?? 0),
                'competition_id' => (int)($row->competition_id ?? 0),
                'kind' => (string)($row->kind ?? ''),
                'title' => (string)($row->title ?? ''),
                'amount' => $row->amount ?? null,
                'currency' => (string)($row->currency ?? ''),
                'vendor' => (string)($row->vendor ?? ''),
                'paid_at' => (string)($row->paid_at ?? ''),
            ],
            request(),
            ['financial','record','delete']
        );

        return back()->with('success', 'تم حذف السجل ✅');
    }

    public function competitionsRecords(Request $request)
    {
        return $this->competitionsFinancial($request);
    }

    public function competitionsMedia(Request $request)
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $linkedIds = $this->ramadanCompetitionIds($seasonId);
        $competitionId = (int)($request->query('competition_id') ?: ($linkedIds[0] ?? 0));

        $items = DB::table('ramadan_competition_media')
            ->where('season_id', $seasonId)
            ->when($competitionId, fn($q) => $q->where('competition_id', $competitionId))
            ->orderByDesc('id')
            ->get();

        $competitions = DB::table('competitions')->whereIn('id', $linkedIds ?: [0])->orderByDesc('id')->get();

        return $this->view('media', compact('items', 'competitions', 'competitionId'));
    }

    public function mediaStore(Request $request, int $competitionId)
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $data = $request->validate([
            'media_type' => 'required|in:image,video,file,link',
            'file' => 'nullable|file|max:20480',
            'url' => 'nullable|url',
            'caption' => 'nullable|string|max:500',
        ]);

        $path = null;
        if ($request->hasFile('file')) {
            $path = $request->file('file')->store('ramadan/media', 'public');
        } elseif (!empty($data['url'])) {
            $path = $data['url'];
        } else {
            return back()->with('error', 'لازم ملف أو رابط');
        }

        $mediaId = DB::table('ramadan_competition_media')->insertGetId([
            'season_id' => $seasonId,
            'competition_id' => $competitionId ?: null,
            'media_type' => $data['media_type'],
            'path' => $path,
            'thumb_path' => null,
            'caption' => $data['caption'] ?? null,
            'taken_at' => null,
            'uploaded_by' => auth()->id(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $this->notifySuperAdmins("🖼️ إضافة ميديا لمسابقات رمضان (Competition ID: {$competitionId})", route('superadmin.ramadan.competitions.media', ['competition_id'=>$competitionId]), 'fa-photo-film');

        // ✅ AUTO LOG
        $this->safeAutoLog(
            "إضافة ميديا لمسابقات رمضان",
            [
                'media_id' => (int)$mediaId,
                'season_id' => $seasonId,
                'competition_id' => (int)$competitionId,
                'media_type' => $data['media_type'],
                'path' => $path,
                'caption' => $data['caption'] ?? null,
            ],
            $request,
            ['media','create']
        );

        return back()->with('success', 'تم رفع/إضافة الميديا ✅');
    }

    public function mediaDestroy(int $id)
    {
        $row = DB::table('ramadan_competition_media')->where('id', $id)->first();
        DB::table('ramadan_competition_media')->where('id', $id)->delete();

        // ✅ AUTO LOG
        $this->safeAutoLog(
            "حذف ميديا من مسابقات رمضان",
            [
                'media_id' => (int)$id,
                'season_id' => (int)($row->season_id ?? 0),
                'competition_id' => (int)($row->competition_id ?? 0),
                'media_type' => (string)($row->media_type ?? ''),
                'path' => (string)($row->path ?? ''),
                'caption' => (string)($row->caption ?? ''),
            ],
            request(),
            ['media','delete']
        );

        return back()->with('success', 'تم حذف الميديا ✅');
    }

    /* =========================
     | Log (manual page + auto meta logs)
     ========================= */
    public function logIndex()
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $entries = DB::table('ramadan_log_entries')
            ->where('season_id', $seasonId)
            ->orderByDesc('log_date')
            ->orderByDesc('id')
            ->get();

        return $this->view('log', compact('entries'));
    }

    public function logStore(Request $request)
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $data = $request->validate([
            'log_date' => 'required|date',
            'title' => 'required|string|max:190',
            'body' => 'nullable|string',
            'tags' => 'nullable|string|max:255',
            'is_pinned' => 'nullable|boolean',
        ]);

        $dtJo = $this->jordanNow();

        DB::table('ramadan_log_entries')->insert([
            'season_id' => $seasonId,
            'log_date' => $data['log_date'],
            'title' => $data['title'],
            'body' => $data['body'] ?? null,
            'tags' => $data['tags'] ?? null,
            'is_pinned' => !empty($data['is_pinned']) ? 1 : 0,
            'created_by' => auth()->id(),
            'created_at' => $dtJo->toDateTimeString(),
            'updated_at' => $dtJo->toDateTimeString(),
        ]);

        $this->notifySuperAdmins("📌 إضافة سجل رمضان: {$data['title']}", route('superadmin.ramadan.log.index'), 'fa-book-open');


        return back()->with('success', 'تمت إضافة السجل ✅');
    }

    public function logDestroy(int $id)
    {
        $row = DB::table('ramadan_log_entries')->where('id', $id)->first();
        DB::table('ramadan_log_entries')->where('id', $id)->delete();

            "حذف سجل من سجلات رمضان",
            [
                'deleted_log_id' => (int)$id,
                'season_id' => (int)($row->season_id ?? 0),
                'log_date' => (string)($row->log_date ?? ''),
                'title' => (string)($row->title ?? ''),
                'tags' => (string)($row->tags ?? ''),
                'is_pinned' => (int)($row->is_pinned ?? 0),
                'created_by' => (int)($row->created_by ?? 0),
            ],
            request(),
            ['log','delete']
        );

        return back()->with('success', 'تم حذف السجل ✅');
    }

    /* =========================
     | Participants
     ========================= */
    public function participantsIndex()
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $participants = DB::table('ramadan_participants as rp')
            ->join('users as u', 'u.id', '=', 'rp.user_id')
            ->where('rp.season_id', $seasonId)
            ->select('rp.*', 'u.name', 'u.email', 'u.membership_status', 'u.gender')
            ->orderByDesc('rp.id')
            ->get();

        $users = DB::table('users')->select('id','name','email','membership_status')
            ->where('account_status','active')
            ->orderBy('name')
            ->limit(250)
            ->get();

        return $this->view('participants', compact('participants', 'users'));
    }

    public function participantsStore(Request $request)
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $data = $request->validate([
            'user_id' => 'required|integer',
            'status' => 'nullable|in:active,paused,blocked',
            'notes' => 'nullable|string|max:1000',
        ]);

        DB::table('ramadan_participants')->updateOrInsert(
            ['season_id' => $seasonId, 'user_id' => $data['user_id']],
            [
                'status' => $data['status'] ?? 'active',
                'joined_at' => now(),
                'notes' => $data['notes'] ?? null,
                'created_by' => auth()->id(),
                'created_at' => now(),
                'updated_at' => now(),
            ]
        );

        $this->notifySuperAdmins("👤 إضافة/تحديث مشارك رمضان (User ID: {$data['user_id']})", route('superadmin.ramadan.participants.index'), 'fa-users');

            "إضافة/تحديث مشارك في رمضان",
            [
                'season_id' => $seasonId,
                'target_user_id' => (int)$data['user_id'],
                'target_user_name' => $this->userDisplayName((int)$data['user_id']),
                'status' => $data['status'] ?? 'active',
                'notes' => $data['notes'] ?? null,
            ],
            $request,
            ['participants','upsert']
        );

        return back()->with('success', 'تمت إضافة/تحديث المشارك ✅');
    }

    public function participantsDestroy(int $id)
    {
        $row = DB::table('ramadan_participants')->where('id', $id)->first();
        DB::table('ramadan_participants')->where('id', $id)->delete();

            "حذف مشارك من رمضان",
            [
                'participant_row_id' => (int)$id,
                'season_id' => (int)($row->season_id ?? 0),
                'user_id' => (int)($row->user_id ?? 0),
                'user_name' => $this->userDisplayName((int)($row->user_id ?? 0)),
                'status' => (string)($row->status ?? ''),
                'notes' => (string)($row->notes ?? ''),
            ],
            request(),
            ['participants','delete']
        );

        return back()->with('success', 'تم حذف المشارك ✅');
    }

    public function participantsStats()
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $totals = DB::table('vw_ramadan_participant_totals as t')
            ->join('users as u', 'u.id', '=', 't.user_id')
            ->where('t.season_id', $seasonId)
            ->select('t.*', 'u.name', 'u.membership_status')
            ->orderByDesc('t.total_points')
            ->get();

        return $this->view('stats', compact('totals'));
    }

    public function topTime()
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $scheduled = DB::table('ramadan_schedule_assignments as a')
            ->join('ramadan_schedule_slots as s', 's.id', '=', 'a.slot_id')
            ->where('s.season_id', $seasonId)
            ->select('a.user_id', DB::raw('SUM(s.duration_hours*60 + s.duration_minutes) AS scheduled_minutes'))
            ->groupBy('a.user_id');

        $rows = DB::table('vw_ramadan_participant_totals as t')
            ->join('users as u', 'u.id', '=', 't.user_id')
            ->leftJoinSub($scheduled, 'sch', function($j) {
                $j->on('sch.user_id', '=', 't.user_id');
            })
            ->where('t.season_id', $seasonId)
            ->select(
                't.user_id',
                'u.name',
                DB::raw('COALESCE(t.total_minutes,0) AS total_minutes'),
                DB::raw('COALESCE(sch.scheduled_minutes,0) AS scheduled_minutes'),
                DB::raw('(COALESCE(t.total_minutes,0) + COALESCE(sch.scheduled_minutes,0)) AS grand_minutes')
            )
            ->orderByDesc('grand_minutes')
            ->limit(10)
            ->get();

        return $this->view('top_time', compact('rows'));
    }

    public function topCompetitions()
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $compIds = $this->ramadanCompetitionIds($seasonId);

        $rows = DB::table('competition_participants as cp')
            ->join('users as u', 'u.id', '=', 'cp.user_id')
            ->whereIn('cp.competition_id', $compIds ?: [0])
            ->select('cp.user_id', 'u.name', DB::raw('COUNT(*) AS competitions_count'), DB::raw('SUM(COALESCE(cp.points_awarded,0)) AS points_awarded'))
            ->groupBy('cp.user_id', 'u.name')
            ->orderByDesc('competitions_count')
            ->limit(10)
            ->get();

        return $this->view('top_competitions', compact('rows'));
    }

    /* =========================
     | Baba Ghanouj
     ========================= */
    public function babaGhanoujIndex()
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $posts = DB::table('ramadan_baba_ghanouj_posts')
            ->where('season_id', $seasonId)
            ->orderByDesc('is_pinned')
            ->orderByDesc('id')
            ->get();

        return $this->view('baba', compact('posts'));
    }

    public function babaGhanoujStore(Request $request)
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $data = $request->validate([
            'title' => 'required|string|max:190',
            'body' => 'required|string',
            'mood' => 'nullable|in:fun,challenge,tip,story,other',
            'is_pinned' => 'nullable|boolean',
        ]);

        $postId = DB::table('ramadan_baba_ghanouj_posts')->insertGetId([
            'season_id' => $seasonId,
            'title' => $data['title'],
            'body' => $data['body'],
            'mood' => $data['mood'] ?? 'fun',
            'is_pinned' => !empty($data['is_pinned']) ? 1 : 0,
            'publish_at' => now(),
            'created_by' => auth()->id(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $this->notifySuperAdmins("🌶️ بابا غنوج: منشور جديد ({$data['title']})", route('superadmin.ramadan.baba-ghanouj.index'), 'fa-pepper-hot');

            "إضافة منشور بابا غنوج",
            [
                'post_id' => (int)$postId,
                'season_id' => $seasonId,
                'title' => $data['title'],
                'mood' => $data['mood'] ?? 'fun',
                'is_pinned' => !empty($data['is_pinned']) ? 1 : 0,
            ],
            $request,
            ['baba','create']
        );

        return back()->with('success', 'تم إضافة المنشور ✅');
    }

    public function babaGhanoujDestroy(int $id)
    {
        $row = DB::table('ramadan_baba_ghanouj_posts')->where('id', $id)->first();
        DB::table('ramadan_baba_ghanouj_posts')->where('id', $id)->delete();

            "حذف منشور بابا غنوج",
            [
                'post_id' => (int)$id,
                'season_id' => (int)($row->season_id ?? 0),
                'title' => (string)($row->title ?? ''),
                'mood' => (string)($row->mood ?? ''),
                'is_pinned' => (int)($row->is_pinned ?? 0),
            ],
            request(),
            ['baba','delete']
        );

        return back()->with('success', 'تم حذف المنشور ✅');
    }

    /* =========================
     | Schedule => ✅ live_streams
     ========================= */
    public function scheduleIndex()
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $slots = DB::table('ramadan_schedule_slots')
            ->where('season_id', $seasonId)
            ->orderBy('scheduled_date')
            ->orderBy('scheduled_time')
            ->get();

        $assignments = DB::table('ramadan_schedule_assignments as a')
            ->join('users as u', 'u.id', '=', 'a.user_id')
            ->select('a.*', 'u.name')
            ->orderByDesc('a.id')
            ->get()
            ->groupBy('slot_id');

        $activityTypes = DB::table('activity_types')->select('id','name','display_name')->orderBy('id')->get();

        $users = User::query()
            ->where('account_status','active')
            ->orderByRaw('COALESCE(name,username) ASC')
            ->get(['id','name','username','avatar']);

        $date = request()->get('scheduled_date', now()->toDateString());
        $absentUserIds = $this->usersWithApprovedAbsenceOnDate($users->pluck('id')->all(), $date);

        return $this->view('schedule', compact('slots','assignments','activityTypes','users','absentUserIds','date'));
    }

    public function scheduleStore(Request $request)
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $data = $request->validate([
            'scheduled_date' => 'required|date',
            'scheduled_time' => 'required',
            'duration_hours' => 'required|integer|min:0|max:24',
            'duration_minutes' => 'required|integer|min:0|max:59',
            'slot_label' => 'required|string|max:190',
            'activity_type_id' => 'nullable|integer',
            'is_sahra' => 'nullable|boolean',
            'sahra_topics' => 'nullable|string|max:500',
            'status' => 'nullable|in:draft,published,locked,cancelled',
        ]);

        $slotId = DB::table('ramadan_schedule_slots')->insertGetId([
            'season_id' => $seasonId,
            'activity_type_id' => $data['activity_type_id'] ?? null,
            'scheduled_date' => $data['scheduled_date'],
            'scheduled_time' => $data['scheduled_time'],
            'duration_hours' => (int)$data['duration_hours'],
            'duration_minutes' => (int)$data['duration_minutes'],
            'slot_label' => $data['slot_label'],
            'is_sahra' => !empty($data['is_sahra']) ? 1 : 0,
            'sahra_topics' => $data['sahra_topics'] ?? null,
            'status' => $data['status'] ?? 'draft',
            'live_activity_id' => null,
            'created_by' => auth()->id(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $this->notifySuperAdmins("🗓️ إضافة سلوّت/ساعة رمضان: {$data['slot_label']}", route('superadmin.ramadan.schedule.index'), 'fa-calendar-days');

            "إضافة ساعة/سلوّت رمضان",
            [
                'slot_id' => (int)$slotId,
                'season_id' => $seasonId,
                'slot_label' => $data['slot_label'],
                'scheduled_date' => $data['scheduled_date'],
                'scheduled_time' => $data['scheduled_time'],
                'duration_hours' => (int)$data['duration_hours'],
                'duration_minutes' => (int)$data['duration_minutes'],
                'is_sahra' => !empty($data['is_sahra']) ? 1 : 0,
                'sahra_topics' => $data['sahra_topics'] ?? null,
                'status' => $data['status'] ?? 'draft',
                'activity_type_id' => $data['activity_type_id'] ?? null,
            ],
            $request,
            ['schedule','slot','create']
        );

        return back()->with('success', 'تمت إضافة الساعة ✅');
    }

    public function scheduleAssign(Request $request, int $slotId)
    {
        $data = $request->validate([
            'user_id' => 'required|integer|exists:users,id',
            'send_notification' => 'nullable|boolean',
        ]);

        $actorId = (int) auth()->id();
        $userId  = (int) $data['user_id'];

        $payload = DB::transaction(function () use ($request, $slotId, $userId, $actorId) {

            $slot = DB::table('ramadan_schedule_slots')->where('id', $slotId)->lockForUpdate()->first();
            if (!$slot) abort(404, 'Slot غير موجود');

            $date = (string)($slot->scheduled_date ?? '');
            $time = (string)($slot->scheduled_time ?? '');

            if ($date === '' || $time === '') {
                abort(422, 'slot بدون تاريخ/وقت');
            }

            if ($this->userHasApprovedAbsenceOnDate($userId, $date)) {
                $name = $this->userDisplayName($userId);
                throw ValidationException::withMessages([
                    'user_id' => ["لا يمكن تعيين ساعة رمضان بتاريخ {$date}: العضو ({$name}) في فترة غياب مُعتمدة تغطي هذا اليوم."],
                ]);
            }

            $exists = LiveStream::query()
                ->whereNull('deleted_at')
                ->where('user_id', $userId)
                ->whereDate('scheduled_date', $date)
                ->where('scheduled_time', $time)
                ->exists();

            if ($exists) {
                throw ValidationException::withMessages([
                    'scheduled_time' => ["لا يمكن إنشاء لايف: يوجد لايف مسبق لنفس العضو بنفس التاريخ والوقت ({$date} {$time})."],
                ]);
            }

            $planned = $this->plannedHours((int)$slot->duration_hours, (int)$slot->duration_minutes);
            [$h, $m] = $this->hoursToHM((float)$planned);

            $isSahra = ((int)($slot->is_sahra ?? 0) === 1);
            $topics  = (string)($slot->sahra_topics ?? '');

            $noteClean = null;
            if ($isSahra) {
                $noteClean = trim(
                    "<span style='color:#d97706;font-weight:bold;'>سهرة رمضانية :</span> " .
                    e($topics !== '' ? $topics : ($slot->slot_label ?? ''))
                );
            }

            $slotLabel = $slot->slot_label ?? null;

            $live = LiveStream::create([
                'user_id'          => $userId,
                'assigned_by'      => $actorId,
                'scheduled_date'   => $date,
                'scheduled_time'   => $time,
                'slot_label'       => $slotLabel ? Str::limit((string)$slotLabel, 50, '') : null,
                'duration_hours'   => $h,
                'duration_minutes' => $m,
                'type'             => 'guests',
                'is_sahra'         => $isSahra ? 1 : 0,
                'sahra_topics'     => $isSahra ? ($topics ?: null) : null,
                'status'           => 'scheduled',
                'description'      => $noteClean,
                'points_earned'    => 0,
            ]);

            $this->logAction(
                (int)$live->id,
                $actorId,
                'created_from_ramadan_slot',
                null,
                'scheduled',
                0,
                (float)$planned,
                $isSahra ? ('سهرة رمضانية: ' . ($topics ?: $slotLabel)) : null,
                $request
            );

            DB::table('ramadan_schedule_slots')->where('id', $slotId)->update([
                'live_activity_id' => (int)$live->id,
                'updated_at' => now(),
            ]);

            DB::table('ramadan_schedule_assignments')->updateOrInsert(
                ['slot_id' => $slotId, 'user_id' => $userId],
                [
                    'live_activity_id' => (int)$live->id,
                    'activity_participant_id' => null,
                    'assigned_by' => $actorId,
                    'status' => 'invited',
                    'notes' => $isSahra ? ('سهرة رمضانية: ' . ($topics ?: $slotLabel)) : null,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]
            );

            return [
                'slot_id' => (int)$slotId,
                'live_id' => (int)$live->id,
                'date' => $date,
                'time' => $time,
                'slot_label' => (string)($slotLabel ?? ''),
                'is_sahra' => $isSahra,
                'topics' => $topics,
                'duration_hours' => (int)$h,
                'duration_minutes' => (int)$m,
                'planned_hours' => (float)$planned,
            ];
        });

        SuperAdminNotificationService::notifyLiveStatus(
            (int)$payload['live_id'],
            'scheduled',
            (int) auth()->id()
        );

        if (!empty($data['send_notification'])) {
            $msg = "تم تكليفك بساعة رمضان: {$payload['slot_label']} بتاريخ {$payload['date']} {$payload['time']}";
            if (!empty($payload['is_sahra'])) {
                $msg .= " — سهرة رمضانية: " . ($payload['topics'] ?: $payload['slot_label']);
            }
            $this->createManualNotification('تكليف ساعة رمضان', $msg, 'specific_users', [$userId]);
            $this->createHubNotification('reminder', 'تكليف ساعة رمضان', $msg, 'all', null, null, [
                'target_user_id' => $userId,
                'slot_id' => (int)$slotId,
                'live_stream_id' => (int)$payload['live_id'],
            ]);
        }

        $this->notifySuperAdmins(
            "✅ تم إنشاء لايف من ساعة رمضان وربطه (Slot ID: {$slotId} → Live ID: {$payload['live_id']})",
            route('superadmin.falcon-room.lives-new.confirm', ['date' => $payload['date']]),
            'fa-video'
        );

            "قام {$this->userDisplayName($actorId)} بربط ساعة لايف لعضو {$this->userDisplayName($userId)} بمناسبة شهر رمضان",
            [
                'slot_id' => (int)$payload['slot_id'],
                'slot_label' => $payload['slot_label'],
                'slot_scheduled_date' => $payload['date'],
                'slot_scheduled_time' => $payload['time'],
                'live_id' => (int)$payload['live_id'],
                'live_status' => 'scheduled',
                'assigned_user_id' => $userId,
                'assigned_user_name' => $this->userDisplayName($userId),
                'is_sahra' => (int)$payload['is_sahra'],
                'sahra_topics' => $payload['topics'] ?: null,
                'duration_hours' => (int)$payload['duration_hours'],
                'duration_minutes' => (int)$payload['duration_minutes'],
                'planned_hours' => (float)$payload['planned_hours'],
                'send_notification' => !empty($data['send_notification']) ? 1 : 0,
            ],
            $request,
            ['schedule','assign','live']
        );

        return back()->with('success', 'تم إنشاء لايف وربطه بساعة رمضان ✅');
    }

    public function scheduleUnassign(Request $request, int $id)
    {
        $row = DB::table('ramadan_schedule_assignments')->where('id', $id)->first();
        if (!$row) return back()->with('error', 'التعيين غير موجود');

        DB::table('ramadan_schedule_assignments')->where('id', $id)->delete();

        $this->notifySuperAdmins(
            "⛔ تم إلغاء تعيين ساعة رمضان (Assignment ID: {$id})",
            route('superadmin.ramadan.schedule.index'),
            'fa-user-xmark'
        );

            "إلغاء ربط/تعيين ساعة رمضان",
            [
                'assignment_id' => (int)$id,
                'slot_id' => (int)($row->slot_id ?? 0),
                'user_id' => (int)($row->user_id ?? 0),
                'user_name' => $this->userDisplayName((int)($row->user_id ?? 0)),
                'live_stream_id' => (int)($row->live_activity_id ?? 0),
                'status' => (string)($row->status ?? ''),
                'notes' => (string)($row->notes ?? ''),
            ],
            $request,
            ['schedule','unassign','delete']
        );

        return back()->with('success', 'تم إلغاء التعيين ✅');
    }

    /* =========================
     | Certificates
     ========================= */
    public function certificatesIndex()
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $items = DB::table('ramadan_certificates as c')
            ->join('users as u', 'u.id', '=', 'c.user_id')
            ->where('c.season_id', $seasonId)
            ->select('c.*', 'u.name')
            ->orderByDesc('c.id')
            ->get();

        $users = DB::table('users')->select('id','name')->where('account_status','active')->orderBy('name')->limit(250)->get();

        return $this->view('certificates', compact('items','users'));
    }

    public function certificatesStore(Request $request)
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $data = $request->validate([
            'user_id' => 'required|integer',
            'title' => 'required|string|max:190',
            'reason' => 'nullable|string|max:500',
        ]);

        $certId = DB::table('ramadan_certificates')->insertGetId([
            'season_id' => $seasonId,
            'user_id' => $data['user_id'],
            'title' => $data['title'],
            'reason' => $data['reason'] ?? null,
            'template' => 'ramadan_default',
            'file_path' => null,
            'issued_at' => now(),
            'issued_by' => auth()->id(),
            'meta_json' => null,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $this->notifySuperAdmins("🏅 إصدار شهادة رمضان (User ID: {$data['user_id']})", route('superadmin.ramadan.certificates.index'), 'fa-certificate');

            "إصدار شهادة رمضان لعضو {$this->userDisplayName((int)$data['user_id'])}",
            [
                'certificate_id' => (int)$certId,
                'season_id' => $seasonId,
                'user_id' => (int)$data['user_id'],
                'user_name' => $this->userDisplayName((int)$data['user_id']),
                'title' => $data['title'],
                'reason' => $data['reason'] ?? null,
            ],
            $request,
            ['certificates','create']
        );

        return back()->with('success', 'تم إصدار الشهادة ✅');
    }

    public function certificatesDestroy(int $id)
    {
        $row = DB::table('ramadan_certificates')->where('id', $id)->first();
        DB::table('ramadan_certificates')->where('id', $id)->delete();

            "حذف شهادة رمضان",
            [
                'certificate_id' => (int)$id,
                'season_id' => (int)($row->season_id ?? 0),
                'user_id' => (int)($row->user_id ?? 0),
                'user_name' => $this->userDisplayName((int)($row->user_id ?? 0)),
                'title' => (string)($row->title ?? ''),
                'reason' => (string)($row->reason ?? ''),
            ],
            request(),
            ['certificates','delete']
        );

        return back()->with('success', 'تم حذف الشهادة ✅');
    }

    /* =========================
     | Honors
     ========================= */
    public function honorsIndex()
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $links = DB::table('ramadan_honor_links as l')
            ->join('honors_rewards as hr', 'hr.id', '=', 'l.honor_reward_id')
            ->where('l.season_id', $seasonId)
            ->select('l.*', 'hr.title as honor_title', 'hr.type', 'hr.reward_type', 'hr.reward_value')
            ->orderByDesc('l.id')
            ->get();

        $all = DB::table('honors_rewards')->orderByDesc('id')->limit(200)->get();

        return $this->view('honors', compact('links','all'));
    }

    public function honorLinkStore(Request $request)
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $data = $request->validate([
            'honor_reward_id' => 'required|integer',
        ]);

        DB::table('ramadan_honor_links')->updateOrInsert(
            ['season_id' => $seasonId, 'honor_reward_id' => $data['honor_reward_id']],
            ['created_by' => auth()->id(), 'created_at' => now(), 'updated_at' => now()]
        );

        $this->notifySuperAdmins("👑 ربط تكريم/جائزة برمضان (Honor ID: {$data['honor_reward_id']})", route('superadmin.ramadan.honors.index'), 'fa-crown');

            "ربط تكريم/جائزة بموسم رمضان",
            [
                'season_id' => $seasonId,
                'honor_reward_id' => (int)$data['honor_reward_id'],
            ],
            $request,
            ['honors','link']
        );

        return back()->with('success', 'تم الربط ✅');
    }

    public function honorLinkDestroy(int $id)
    {
        $row = DB::table('ramadan_honor_links')->where('id', $id)->first();
        DB::table('ramadan_honor_links')->where('id', $id)->delete();

            "فك ربط تكريم/جائزة عن موسم رمضان",
            [
                'link_id' => (int)$id,
                'season_id' => (int)($row->season_id ?? 0),
                'honor_reward_id' => (int)($row->honor_reward_id ?? 0),
            ],
            request(),
            ['honors','unlink','delete']
        );

        return back()->with('success', 'تم فك الربط ✅');
    }

    /* =========================
     | Alerts
     ========================= */
    public function alertsIndex()
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $alerts = DB::table('ramadan_alerts')
            ->where('season_id', $seasonId)
            ->orderByDesc('id')
            ->get();

        return $this->view('alerts', compact('alerts'));
    }

    public function alertsStore(Request $request)
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $data = $request->validate([
            'server_key' => 'nullable|string|max:100',
            'title' => 'required|string|max:190',
            'body' => 'required|string',
            'audience' => 'required|in:all,moderators,beta,male,female',
            'send_at' => 'nullable|date',
        ]);

        $alertId = DB::table('ramadan_alerts')->insertGetId([
            'season_id' => $seasonId,
            'server_key' => $data['server_key'] ?? null,
            'title' => $data['title'],
            'body' => $data['body'],
            'audience' => $data['audience'],
            'send_at' => $data['send_at'] ?? null,
            'status' => $data['send_at'] ? 'scheduled' : 'draft',
            'notification_hub_notification_id' => null,
            'manual_notification_id' => null,
            'created_by' => auth()->id(),
            'sent_by' => null,
            'sent_at' => null,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $this->notifySuperAdmins("🔔 تم إنشاء تنبيه رمضان: {$data['title']}", route('superadmin.ramadan.alerts.index'), 'fa-bell');

            "إنشاء تنبيه رمضان",
            [
                'alert_id' => (int)$alertId,
                'season_id' => $seasonId,
                'server_key' => $data['server_key'] ?? null,
                'title' => $data['title'],
                'audience' => $data['audience'],
                'send_at' => $data['send_at'] ?? null,
                'status' => $data['send_at'] ? 'scheduled' : 'draft',
            ],
            $request,
            ['alerts','create']
        );

        return back()->with('success', 'تم إنشاء التنبيه ✅');
    }

    public function alertsSend(int $id)
    {
        $alert = DB::table('ramadan_alerts')->where('id', $id)->first();
        if (!$alert) return back()->with('error', 'تنبيه غير موجود');

        $aud = $alert->audience;
        $userIds = $this->usersByAudience($aud);

        $manualId = $this->createManualNotification(
            $alert->title,
            $alert->body,
            $aud === 'all' ? 'all' : ($aud === 'moderators' ? 'moderators' : 'members'),
            $userIds
        );

        $hubId = $this->createHubNotification(
            'custom',
            $alert->title,
            $alert->body,
            $aud,
            route('superadmin.ramadan.alerts.index'),
            $alert->send_at ? date('Y-m-d H:i:s', strtotime($alert->send_at)) : null,
            ['server_key' => $alert->server_key, 'ramadan_alert_id' => (int)$id]
        );

        DB::table('ramadan_alerts')->where('id', $id)->update([
            'status' => $alert->send_at ? 'scheduled' : 'sent',
            'notification_hub_notification_id' => $hubId,
            'manual_notification_id' => $manualId,
            'sent_by' => auth()->id(),
            'sent_at' => $alert->send_at ? null : now(),
            'updated_at' => now(),
        ]);

        $this->notifySuperAdmins("✅ تم إرسال/جدولة تنبيه رمضان: {$alert->title}", route('superadmin.ramadan.alerts.index'), 'fa-bell');

            $alert->send_at ? "جدولة إرسال تنبيه رمضان" : "إرسال تنبيه رمضان",
            [
                'alert_id' => (int)$id,
                'season_id' => (int)($alert->season_id ?? 0),
                'title' => (string)($alert->title ?? ''),
                'audience' => (string)($alert->audience ?? ''),
                'send_at' => (string)($alert->send_at ?? ''),
                'status' => $alert->send_at ? 'scheduled' : 'sent',
                'manual_notification_id' => (int)$manualId,
                'notification_hub_notification_id' => (int)$hubId,
                'recipients_count' => count($userIds),
            ],
            request(),
            ['alerts','send']
        );

        return back()->with('success', 'تم إرسال/جدولة التنبيه ✅');
    }

    public function alertsDestroy(int $id)
    {
        $row = DB::table('ramadan_alerts')->where('id', $id)->first();
        DB::table('ramadan_alerts')->where('id', $id)->delete();

            "حذف تنبيه رمضان",
            [
                'alert_id' => (int)$id,
                'season_id' => (int)($row->season_id ?? 0),
                'title' => (string)($row->title ?? ''),
                'audience' => (string)($row->audience ?? ''),
                'status' => (string)($row->status ?? ''),
                'send_at' => (string)($row->send_at ?? ''),
            ],
            request(),
            ['alerts','delete']
        );

        return back()->with('success', 'تم حذف التنبيه ✅');
    }

    /* =========================
     | Missions
     ========================= */
    public function missionsIndex()
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $missions = DB::table('ramadan_missions')->where('season_id', $seasonId)->orderByDesc('id')->get();

        $assignments = DB::table('ramadan_mission_assignments as a')
            ->join('ramadan_missions as m', 'm.id', '=', 'a.mission_id')
            ->join('users as u', 'u.id', '=', 'a.user_id')
            ->where('m.season_id', $seasonId)
            ->select('a.*','m.title as mission_title','u.name')
            ->orderByDesc('a.id')
            ->get();

        $users = DB::table('users')->select('id','name')->where('account_status','active')->orderBy('name')->limit(250)->get();

        return $this->view('missions', compact('missions','assignments','users'));
    }

    public function missionsStore(Request $request)
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $data = $request->validate([
            'title' => 'required|string|max:190',
            'description' => 'nullable|string',
            'points_reward' => 'required|integer|min:0',
            'minutes_reward' => 'required|integer|min:0',
            'due_at' => 'nullable|date',
        ]);

        $missionId = DB::table('ramadan_missions')->insertGetId([
            'season_id' => $seasonId,
            'title' => $data['title'],
            'description' => $data['description'] ?? null,
            'points_reward' => (int)$data['points_reward'],
            'minutes_reward' => (int)$data['minutes_reward'],
            'due_at' => $data['due_at'] ?? null,
            'status' => 'open',
            'created_by' => auth()->id(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $this->notifySuperAdmins("🧩 مهمة رمضان جديدة: {$data['title']}", route('superadmin.ramadan.missions.index'), 'fa-list-check');

            "إنشاء مهمة رمضان جديدة",
            [
                'mission_id' => (int)$missionId,
                'season_id' => $seasonId,
                'title' => $data['title'],
                'points_reward' => (int)$data['points_reward'],
                'minutes_reward' => (int)$data['minutes_reward'],
                'due_at' => $data['due_at'] ?? null,
            ],
            $request,
            ['missions','create']
        );

        return back()->with('success', 'تم إنشاء المهمة ✅');
    }

    public function missionsAssign(Request $request, int $missionId)
    {
        $data = $request->validate([
            'user_id' => 'required|integer',
        ]);

        DB::table('ramadan_mission_assignments')->updateOrInsert(
            ['mission_id' => $missionId, 'user_id' => $data['user_id']],
            ['status' => 'assigned', 'created_at' => now(), 'updated_at' => now()]
        );

        $this->createManualNotification(
            'مهمة رمضان جديدة',
            "تم تكليفك بمهمة رمضانية (ID: {$missionId})",
            'specific_users',
            [(int)$data['user_id']]
        );

        $this->notifySuperAdmins("✅ تعيين مهمة رمضان (Mission ID: {$missionId}, User ID: {$data['user_id']})", route('superadmin.ramadan.missions.index'), 'fa-user-check');

            "تعيين مهمة رمضان لعضو {$this->userDisplayName((int)$data['user_id'])}",
            [
                'mission_id' => (int)$missionId,
                'user_id' => (int)$data['user_id'],
                'user_name' => $this->userDisplayName((int)$data['user_id']),
            ],
            $request,
            ['missions','assign']
        );

        return back()->with('success', 'تم تعيين المهمة ✅');
    }

    public function missionsMarkDone(int $id)
    {
        $assignment = DB::table('ramadan_mission_assignments')->where('id', $id)->first();
        if (!$assignment) return back()->with('error', 'Assignment غير موجود');

        $mission = DB::table('ramadan_missions')->where('id', $assignment->mission_id)->first();
        if (!$mission) return back()->with('error', 'Mission غير موجود');

        DB::table('ramadan_mission_assignments')->where('id', $id)->update([
            'status' => 'done',
            'completed_at' => now(),
            'reviewed_by' => auth()->id(),
            'reviewed_at' => now(),
            'updated_at' => now(),
        ]);

        DB::table('ramadan_points_events')->insert([
            'season_id' => $mission->season_id,
            'user_id' => $assignment->user_id,
            'source_type' => 'mission',
            'source_id' => $mission->id,
            'points' => (int)$mission->points_reward,
            'minutes' => (int)$mission->minutes_reward,
            'note' => 'Mission completed: ' . $mission->title,
            'created_by' => auth()->id(),
            'created_at' => now(),
        ]);

        $this->notifySuperAdmins("🏁 إنجاز مهمة رمضان (Assignment ID: {$id})", route('superadmin.ramadan.missions.index'), 'fa-flag-checkered');

            "اعتماد إنجاز مهمة رمضان",
            [
                'assignment_id' => (int)$id,
                'mission_id' => (int)($mission->id ?? 0),
                'mission_title' => (string)($mission->title ?? ''),
                'season_id' => (int)($mission->season_id ?? 0),
                'user_id' => (int)($assignment->user_id ?? 0),
                'user_name' => $this->userDisplayName((int)($assignment->user_id ?? 0)),
                'points_reward' => (int)($mission->points_reward ?? 0),
                'minutes_reward' => (int)($mission->minutes_reward ?? 0),
            ],
            request(),
            ['missions','done','points']
        );

        return back()->with('success', 'تم اعتماد الإنجاز + إضافة نقاط/دقائق ✅');
    }

    /* =========================
     | Archive
     ========================= */
    public function archiveIndex()
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $items = DB::table('ramadan_archive_items')->where('season_id', $seasonId)->orderByDesc('id')->get();
        return $this->view('archive', compact('items'));
    }

    public function archiveStore(Request $request)
    {
        $season = $this->activeSeason();
        $seasonId = (int)$season->id;

        $data = $request->validate([
            'category' => 'nullable|string|max:80',
            'item_type' => 'required|in:image,video,file,link,text',
            'title' => 'required|string|max:190',
            'body' => 'nullable|string',
            'file' => 'nullable|file|max:20480',
            'url' => 'nullable|url|max:500',
        ]);

        $path = null;
        if ($request->hasFile('file')) {
            $path = $request->file('file')->store('ramadan/archive', 'public');
        }

        $itemId = DB::table('ramadan_archive_items')->insertGetId([
            'season_id' => $seasonId,
            'category' => $data['category'] ?? 'general',
            'item_type' => $data['item_type'],
            'title' => $data['title'],
            'body' => $data['body'] ?? null,
            'path' => $path,
            'url' => $data['url'] ?? null,
            'created_by' => auth()->id(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $this->notifySuperAdmins("🗃️ إضافة عنصر أرشيف رمضان: {$data['title']}", route('superadmin.ramadan.archive.index'), 'fa-box-archive');

            "إضافة عنصر إلى أرشيف رمضان",
            [
                'archive_item_id' => (int)$itemId,
                'season_id' => $seasonId,
                'category' => $data['category'] ?? 'general',
                'item_type' => $data['item_type'],
                'title' => $data['title'],
                'url' => $data['url'] ?? null,
                'path' => $path,
            ],
            $request,
            ['archive','create']
        );

        return back()->with('success', 'تمت الإضافة للأرشيف ✅');
    }

    public function archiveDestroy(int $id)
    {
        $row = DB::table('ramadan_archive_items')->where('id', $id)->first();
        DB::table('ramadan_archive_items')->where('id', $id)->delete();

            "حذف عنصر من أرشيف رمضان",
            [
                'archive_item_id' => (int)$id,
                'season_id' => (int)($row->season_id ?? 0),
                'category' => (string)($row->category ?? ''),
                'item_type' => (string)($row->item_type ?? ''),
                'title' => (string)($row->title ?? ''),
                'url' => (string)($row->url ?? ''),
                'path' => (string)($row->path ?? ''),
            ],
            request(),
            ['archive','delete']
        );

        return back()->with('success', 'تم حذف عنصر الأرشيف ✅');
    }

    /* =========================================================
       Helpers copied from LivesNewController
    ========================================================= */
    private function plannedHours(int $h, int $m): float
    {
        return round($h + ($m / 60), 2);
    }

    private function hoursToHM(float $hours): array
    {
        $h = (int) floor($hours);
        $m = (int) round(($hours - $h) * 60);
        if ($m === 60) { $h += 1; $m = 0; }
        return [$h,$m];
    }

    private function sanitizeHtml(?string $html): ?string
    {
        if ($html === null) return null;
        $allowed = '<b><strong><i><em><u><br><span><small><code><a><ul><ol><li>';
        $clean   = strip_tags((string)$html, $allowed);
        $clean   = preg_replace('/on\w+\s*=\s*"[^"]*"/i','',$clean);
        $clean   = preg_replace("/on\w+\s*=\s*'[^']*'/i",'',$clean);
        $clean   = preg_replace('/javascript\s*:/i','',$clean);
        return $clean;
    }

    private function logAction(
        int $liveId,
        int $actorId,
        string $action,
        ?string $oldStatus,
        ?string $newStatus,
        int $delta,
        float $hours,
        ?string $note,
        Request $req
    ): void {
        DB::table('live_stream_action_logs')->insert([
            'live_stream_id' => $liveId,
            'actor_id'       => $actorId,
            'action'         => $action,
            'old_status'     => $oldStatus,
            'new_status'     => $newStatus,
            'points_delta'   => $delta,
            'hours'          => $hours,
            'note'           => $note,
            'ip_address'     => $req->ip(),
            'user_agent'     => substr((string)$req->userAgent(),0,255),
            'created_at'     => now(),
            'updated_at'     => now(),
        ]);
    }

    private function userHasApprovedAbsenceOnDate(int $userId, string $dateYmd): bool
    {
        return ExcusedAbsence::query()
            ->where('user_id', $userId)
            ->where('status', 'approved')
            ->whereDate('from_date', '<=', $dateYmd)
            ->whereDate('to_date', '>=', $dateYmd)
            ->exists();
    }

    private function usersWithApprovedAbsenceOnDate(array $userIds, string $dateYmd): array
    {
        if (empty($userIds)) return [];

        return ExcusedAbsence::query()
            ->whereIn('user_id', $userIds)
            ->where('status', 'approved')
            ->whereDate('from_date', '<=', $dateYmd)
            ->whereDate('to_date', '>=', $dateYmd)
            ->pluck('user_id')
            ->unique()
            ->values()
            ->all();
    }
}