#!/usr/bin/env bash
set -Eeuo pipefail

APP_DIR="${1:-$(pwd)}"
APP_DIR="${APP_DIR%/}"

if [[ ! -d "$APP_DIR" ]]; then
  echo "❌ المسار غير موجود: $APP_DIR" >&2
  exit 1
fi
cd "$APP_DIR"

if [[ ! -f artisan ]]; then
  echo "❌ لازم تشغّل الباتش من جذر Laravel، المكان اللي فيه artisan" >&2
  echo "مثال: bash install_proactive_dashboard_reports_v5.sh /home/amiros/public_html/portal.amir-os.com" >&2
  exit 1
fi

TS="$(date +%Y%m%d_%H%M%S)"
BACKUP_DIR="$APP_DIR/proactive_dashboard_reports_backup_$TS"
mkdir -p "$BACKUP_DIR"

backup_file() {
  local f="$1"
  if [[ -f "$f" ]]; then
    mkdir -p "$BACKUP_DIR/$(dirname "$f")"
    cp -a "$f" "$BACKUP_DIR/$f"
  fi
}

echo "🦅 تركيب باتش ProActive Dashboard Reports v5..."
echo "📦 Backup: $BACKUP_DIR"

# ملفات مستهدفة
LAYOUT="resources/views/layouts/superadmin.blade.php"
SCHEDULE_VIEW="resources/views/superadmin/proactive/schedules/index.blade.php"
SCHEDULE_CONTROLLER="app/Http/Controllers/SuperAdmin/ProactiveScheduleController.php"

backup_file "$LAYOUT"
backup_file "$SCHEDULE_VIEW"
backup_file "$SCHEDULE_CONTROLLER"

mkdir -p resources/views/superadmin/partials
mkdir -p resources/views/superadmin/proactive/schedules

cat > resources/views/superadmin/partials/proactive_dashboard_reminders.blade.php <<'BLADE'
{{-- PROACTIVE_DASHBOARD_REMINDERS_PARTIAL_V5 --}}
@php
  $__proactiveReady = false;
  $__todayRows = collect();
  $__activeRows = collect();
  $__noReportRows = collect();
  $__staleActiveRows = collect();
  $__reportsUrl = url('/superadmin/proactive-reports');
  $__schedulesUrl = url('/superadmin/proactive/schedules');

  try {
      $__tz = config('app.timezone', 'Asia/Jerusalem');
      $__now = \Carbon\Carbon::now($__tz);
      $__today = $__now->toDateString();
      $__fromNoReport = $__now->copy()->subDays(14)->toDateString();

      foreach ([
          'superadmin.proactive.reports.index',
          'superadmin.proactiveReports.index',
          'superadmin.proactive.reports',
          'superadmin.proactiveReports',
      ] as $__r) {
          if (\Illuminate\Support\Facades\Route::has($__r)) { $__reportsUrl = route($__r); break; }
      }
      if (\Illuminate\Support\Facades\Route::has('superadmin.proactive.schedules.index')) {
          $__schedulesUrl = route('superadmin.proactive.schedules.index');
      } elseif (\Illuminate\Support\Facades\Route::has('superadmin.proactive.grid')) {
          $__schedulesUrl = route('superadmin.proactive.grid');
      }

      if (\Illuminate\Support\Facades\Schema::hasTable('proactive_schedules')) {
          $__proactiveReady = true;

          $__todayRows = \Illuminate\Support\Facades\DB::table('proactive_schedules')
              ->whereDate('event_date', $__today)
              ->whereIn('status', ['upcoming','active','finished'])
              ->orderByRaw("FIELD(status,'active','upcoming','finished','cancelled')")
              ->orderByRaw("COALESCE(event_time,'00:00:00') ASC")
              ->limit(6)
              ->get();

          $__activeRows = \Illuminate\Support\Facades\DB::table('proactive_schedules')
              ->where('status', 'active')
              ->orderBy('event_date', 'desc')
              ->orderByRaw("COALESCE(event_time,'00:00:00') DESC")
              ->limit(6)
              ->get();

          $__staleActiveRows = \Illuminate\Support\Facades\DB::table('proactive_schedules')
              ->where('status', 'active')
              ->whereDate('event_date', '<', $__today)
              ->orderBy('event_date', 'desc')
              ->limit(6)
              ->get();

          $__hasReportsTable = \Illuminate\Support\Facades\Schema::hasTable('proactive_reports');
          $__reportHasActivityType = $__hasReportsTable && \Illuminate\Support\Facades\Schema::hasColumn('proactive_reports', 'activity_type');
          $__reportHasPlatform = $__hasReportsTable && \Illuminate\Support\Facades\Schema::hasColumn('proactive_reports', 'platform');

          $__noReportQuery = \Illuminate\Support\Facades\DB::table('proactive_schedules as s')
              ->where('s.status', 'finished')
              ->whereDate('s.event_date', '>=', $__fromNoReport)
              ->whereDate('s.event_date', '<=', $__today);

          if ($__hasReportsTable) {
              $__noReportQuery->whereNotExists(function($__q) use ($__reportHasActivityType, $__reportHasPlatform) {
                  $__q->select(\Illuminate\Support\Facades\DB::raw(1))
                     ->from('proactive_reports as r')
                     ->whereColumn('r.activity_date', 's.event_date');
                  if ($__reportHasActivityType) {
                      $__q->whereColumn('r.activity_type', 's.event_type');
                  }
                  if ($__reportHasPlatform) {
                      $__q->whereColumn('r.platform', 's.platform');
                  }
              });
          }

          $__noReportRows = $__noReportQuery
              ->orderBy('s.event_date', 'desc')
              ->orderByRaw("COALESCE(s.event_time,'00:00:00') DESC")
              ->limit(6)
              ->get(['s.id','s.event_title','s.event_type','s.event_date','s.event_time','s.platform','s.leader_name','s.status']);
      }
  } catch (\Throwable $__e) {
      $__proactiveReady = false;
  }

  $__showProactiveReminder = $__proactiveReady && ($__todayRows->count() || $__activeRows->count() || $__noReportRows->count() || $__staleActiveRows->count());
@endphp

@if($__showProactiveReminder)
  <div dir="rtl" class="max-w-7xl mx-auto px-3 sm:px-4 lg:px-6 mt-4 mb-5">
    <div class="relative overflow-hidden rounded-3xl border border-cyan-300/25 bg-gradient-to-br from-slate-950 via-slate-900 to-black shadow-2xl shadow-cyan-500/10 p-4 sm:p-5">
      <div class="pointer-events-none absolute -top-20 -right-16 w-72 h-72 rounded-full bg-cyan-400/15 blur-3xl"></div>
      <div class="pointer-events-none absolute -bottom-24 -left-16 w-72 h-72 rounded-full bg-fuchsia-500/15 blur-3xl"></div>

      <div class="relative flex flex-col lg:flex-row lg:items-start lg:justify-between gap-4">
        <div class="space-y-3 min-w-0">
          <div class="inline-flex items-center gap-2 rounded-full bg-cyan-400/10 border border-cyan-300/20 text-cyan-100 px-3 py-1 text-[11px] font-bold">
            <i class="fa-solid fa-bell"></i>
            تذكير ProActive — الداشبورد
          </div>

          <div class="text-white font-extrabold text-lg sm:text-xl">
            عندك متابعة ProActive اليوم / أو تقارير ناقصة لازم تنكتب
          </div>

          <div class="grid grid-cols-2 sm:grid-cols-4 gap-2 text-center">
            <div class="rounded-2xl bg-white/5 border border-white/10 px-3 py-2">
              <div class="text-[10px] text-white/55">مواعيد اليوم</div>
              <div class="text-cyan-200 font-extrabold text-xl">{{ $__todayRows->count() }}</div>
            </div>
            <div class="rounded-2xl bg-white/5 border border-white/10 px-3 py-2">
              <div class="text-[10px] text-white/55">نشطة الآن</div>
              <div class="text-emerald-200 font-extrabold text-xl">{{ $__activeRows->count() }}</div>
            </div>
            <div class="rounded-2xl bg-white/5 border border-white/10 px-3 py-2">
              <div class="text-[10px] text-white/55">نشطة بتاريخ قديم</div>
              <div class="text-amber-200 font-extrabold text-xl">{{ $__staleActiveRows->count() }}</div>
            </div>
            <div class="rounded-2xl bg-white/5 border border-white/10 px-3 py-2">
              <div class="text-[10px] text-white/55">منتهية بلا تقرير</div>
              <div class="text-rose-200 font-extrabold text-xl">{{ $__noReportRows->count() }}</div>
            </div>
          </div>

          <div class="space-y-2 text-[12px] text-white/80">
            @if($__todayRows->count())
              <div class="rounded-2xl border border-cyan-300/15 bg-cyan-400/5 px-3 py-2">
                <b class="text-cyan-100">اليوم:</b>
                @foreach($__todayRows as $__r)
                  <span class="inline-flex items-center gap-1 ms-2 mb-1 rounded-full bg-black/30 border border-white/10 px-2 py-1">
                    {{ $__r->event_time ? \Carbon\Carbon::parse($__r->event_time)->format('H:i') : 'بدون وقت' }} — {{ $__r->event_title }}
                  </span>
                @endforeach
              </div>
            @endif

            @if($__activeRows->count())
              <div class="rounded-2xl border border-emerald-300/15 bg-emerald-400/5 px-3 py-2">
                <b class="text-emerald-100">في فعالية نشطة:</b>
                تابعها، وإذا انتهت اضغط إنهاء واكتب التقرير.
              </div>
            @endif

            @if($__noReportRows->count())
              <div class="rounded-2xl border border-rose-300/15 bg-rose-400/5 px-3 py-2">
                <b class="text-rose-100">تقارير ناقصة:</b>
                في فعاليات منتهية خلال آخر 14 يوم وما إلها تقرير مطابق بنفس التاريخ/النوع/المنصة.
              </div>
            @endif
          </div>
        </div>

        <div class="relative flex flex-col gap-2 lg:w-56 shrink-0">
          <a href="{{ $__reportsUrl }}" class="inline-flex items-center justify-center rounded-2xl bg-gradient-to-r from-cyan-200 via-emerald-200 to-fuchsia-200 text-slate-950 px-4 py-3 text-sm font-extrabold shadow-lg shadow-cyan-500/10 hover:scale-[1.01] transition">
            <i class="fa-solid fa-file-pen ms-2"></i>
            افتح صفحة التقارير
          </a>
          <a href="{{ $__schedulesUrl }}" class="inline-flex items-center justify-center rounded-2xl bg-white/10 border border-white/15 text-white px-4 py-3 text-sm font-bold hover:bg-white/15 transition">
            <i class="fa-solid fa-calendar-days ms-2"></i>
            افتح المواعيد
          </a>
        </div>
      </div>
    </div>
  </div>
@endif
BLADE

cat > resources/views/superadmin/proactive/schedules/_smart_reminders.blade.php <<'BLADE'
{{-- PROACTIVE_SCHEDULE_SMART_REMINDERS_PARTIAL_V5 --}}
@php
  $__smartReady = false;
  $__todayRows = collect();
  $__noReportRows = collect();
  $__reportsUrl = url('/superadmin/proactive-reports');
  $__todayUrl = request()->fullUrlWithQuery(['from'=>now(config('app.timezone','Asia/Jerusalem'))->toDateString(), 'to'=>now(config('app.timezone','Asia/Jerusalem'))->toDateString()]);
  try {
      $__tz = config('app.timezone', 'Asia/Jerusalem');
      $__today = \Carbon\Carbon::now($__tz)->toDateString();
      foreach ([
          'superadmin.proactive.reports.index',
          'superadmin.proactiveReports.index',
          'superadmin.proactive.reports',
          'superadmin.proactiveReports',
      ] as $__r) {
          if (\Illuminate\Support\Facades\Route::has($__r)) { $__reportsUrl = route($__r); break; }
      }
      if (\Illuminate\Support\Facades\Schema::hasTable('proactive_schedules')) {
          $__smartReady = true;
          $__todayRows = \Illuminate\Support\Facades\DB::table('proactive_schedules')
              ->whereDate('event_date', $__today)
              ->whereIn('status', ['upcoming','active','finished'])
              ->orderByRaw("FIELD(status,'active','upcoming','finished','cancelled')")
              ->orderByRaw("COALESCE(event_time,'00:00:00') ASC")
              ->limit(10)
              ->get();

          $__hasReports = \Illuminate\Support\Facades\Schema::hasTable('proactive_reports');
          $__reportHasActivityType = $__hasReports && \Illuminate\Support\Facades\Schema::hasColumn('proactive_reports', 'activity_type');
          $__reportHasPlatform = $__hasReports && \Illuminate\Support\Facades\Schema::hasColumn('proactive_reports', 'platform');
          $__noReportQuery = \Illuminate\Support\Facades\DB::table('proactive_schedules as s')
              ->where('s.status', 'finished')
              ->whereDate('s.event_date', '>=', \Carbon\Carbon::now($__tz)->subDays(14)->toDateString())
              ->whereDate('s.event_date', '<=', $__today);
          if ($__hasReports) {
              $__noReportQuery->whereNotExists(function($__q) use ($__reportHasActivityType, $__reportHasPlatform) {
                  $__q->select(\Illuminate\Support\Facades\DB::raw(1))->from('proactive_reports as r')
                     ->whereColumn('r.activity_date', 's.event_date');
                  if ($__reportHasActivityType) $__q->whereColumn('r.activity_type', 's.event_type');
                  if ($__reportHasPlatform) $__q->whereColumn('r.platform', 's.platform');
              });
          }
          $__noReportRows = $__noReportQuery->orderBy('s.event_date','desc')->limit(10)->get(['s.*']);
      }
  } catch (\Throwable $__e) { $__smartReady = false; }
@endphp

@if($__smartReady)
  <div class="rounded-3xl border border-cyan-300/20 bg-gradient-to-br from-slate-950 via-slate-900 to-black p-4 shadow-xl shadow-cyan-500/10">
    <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-3">
      <div>
        <div class="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-cyan-400/10 border border-cyan-300/20 text-cyan-100 text-[11px] font-bold">
          <i class="fa-solid fa-shield-halved"></i>
          حارس ProActive الذكي
        </div>
        <div class="mt-2 text-white font-extrabold text-lg">تذكير اليوم + التقارير الناقصة</div>
        <div class="text-white/60 text-xs mt-1">يفحص موعد اليوم، النشطة، والمنتهية بدون تقرير مطابق.</div>
      </div>
      <div class="flex flex-wrap gap-2">
        <a href="{{ request()->url() }}" class="px-3 py-2 rounded-2xl bg-white/10 border border-white/15 text-white text-xs hover:bg-white/15">الكل</a>
        <a href="{{ request()->fullUrlWithQuery(['status'=>'active']) }}" class="px-3 py-2 rounded-2xl bg-cyan-500/20 border border-cyan-300/20 text-cyan-100 text-xs hover:bg-cyan-500/25">النشطة</a>
        <a href="{{ $__todayUrl }}" class="px-3 py-2 rounded-2xl bg-emerald-500/20 border border-emerald-300/20 text-emerald-100 text-xs hover:bg-emerald-500/25">اليوم</a>
        <a href="{{ $__reportsUrl }}" class="px-3 py-2 rounded-2xl bg-fuchsia-500/20 border border-fuchsia-300/20 text-fuchsia-100 text-xs hover:bg-fuchsia-500/25">صفحة التقارير</a>
      </div>
    </div>

    @if($__todayRows->count() || $__noReportRows->count())
      <div class="grid md:grid-cols-2 gap-3 mt-4">
        <div class="rounded-2xl bg-white/5 border border-white/10 p-3">
          <div class="text-cyan-100 font-extrabold text-sm mb-2">📅 مواعيد اليوم: {{ $__todayRows->count() }}</div>
          @forelse($__todayRows as $__r)
            <div class="text-[12px] text-white/75 border-t border-white/10 py-2 first:border-t-0">
              <b class="text-white">{{ $__r->event_title }}</b>
              <span class="text-white/45">— {{ $__r->event_time ? \Carbon\Carbon::parse($__r->event_time)->format('H:i') : 'بدون وقت' }}</span>
              <span class="ms-1 rounded-full px-2 py-0.5 bg-black/30 border border-white/10 text-[10px]">{{ $__r->status }}</span>
            </div>
          @empty
            <div class="text-white/45 text-xs">لا يوجد موعد اليوم.</div>
          @endforelse
        </div>

        <div class="rounded-2xl bg-white/5 border border-white/10 p-3">
          <div class="text-rose-100 font-extrabold text-sm mb-2">📝 منتهية بلا تقرير: {{ $__noReportRows->count() }}</div>
          @forelse($__noReportRows as $__r)
            <div class="text-[12px] text-white/75 border-t border-white/10 py-2 first:border-t-0">
              <b class="text-white">{{ $__r->event_title }}</b>
              <span class="text-white/45">— {{ $__r->event_date }}</span>
            </div>
          @empty
            <div class="text-white/45 text-xs">تمام — لا يوجد تقارير ناقصة حسب الفحص الحالي.</div>
          @endforelse
        </div>
      </div>
    @endif
  </div>
@endif
BLADE

# حقن تنبيه الداشبورد داخل layout
python3 - <<'PY'
from pathlib import Path
layout = Path('resources/views/layouts/superadmin.blade.php')
marker = '{{-- PROACTIVE_DASHBOARD_REMINDERS_V5 --}}'
block = """{{-- PROACTIVE_DASHBOARD_REMINDERS_V5 --}}
@php($__proactiveDashPath = trim(request()->path(), '/'))
@if(request()->routeIs('superadmin.dashboard') || request()->routeIs('dashboard') || in_array($__proactiveDashPath, ['superadmin','superadmin/dashboard','dashboard'], true))
  @include('superadmin.partials.proactive_dashboard_reminders')
@endif
{{-- /PROACTIVE_DASHBOARD_REMINDERS_V5 --}}
"""
if layout.exists():
    s = layout.read_text(encoding='utf-8')
    if marker not in s:
        done = False
        for token in ["@yield('content')", '@yield("content")']:
            if token in s:
                s = s.replace(token, block + "\n" + token, 1)
                done = True
                break
        if not done:
            # آخر حل: قبل إغلاق body
            if '</body>' in s:
                s = s.replace('</body>', block + '\n</body>', 1)
            else:
                s += '\n' + block + '\n'
        layout.write_text(s, encoding='utf-8')
        print('✅ تم حقن تنبيه الداشبورد في layout')
    else:
        print('ℹ️ تنبيه الداشبورد موجود مسبقًا')
else:
    print('⚠️ لم أجد resources/views/layouts/superadmin.blade.php — تم إنشاء الـ partial فقط')
PY

# حقن تنبيه صفحة المواعيد داخل صفحة ProActive
python3 - <<'PY'
from pathlib import Path
view = Path('resources/views/superadmin/proactive/schedules/index.blade.php')
marker = '{{-- PROACTIVE_SCHEDULE_SMART_REMINDERS_V5 --}}'
block = """{{-- PROACTIVE_SCHEDULE_SMART_REMINDERS_V5 --}}
@include('superadmin.proactive.schedules._smart_reminders')
{{-- /PROACTIVE_SCHEDULE_SMART_REMINDERS_V5 --}}
"""
if view.exists():
    s = view.read_text(encoding='utf-8')
    if marker not in s:
        if '{{-- ✅ STATS CARDS' in s:
            s = s.replace('{{-- ✅ STATS CARDS', block + '\n{{-- ✅ STATS CARDS', 1)
        elif '<div class="grid gap-4 lg:grid-cols-3">' in s:
            s = s.replace('<div class="grid gap-4 lg:grid-cols-3">', block + '\n<div class="grid gap-4 lg:grid-cols-3">', 1)
        else:
            s = s.replace('@section(\'content\')', '@section(\'content\')\n' + block, 1)
        print('✅ تم حقن حارس ProActive في صفحة المواعيد')
    else:
        print('ℹ️ حارس ProActive موجود مسبقًا في صفحة المواعيد')

    # إصلاح احتياطي العداد: لا يحسب من تاريخ الموعد إذا started_at فارغ
    old = "data-start=\"{{ $item->started_at ?? ($item->event_date.' '.($item->event_time ?? '00:00:00')) }}\""
    if old in s:
        s = s.replace(old, "data-start=\"{{ $item->started_at }}\"")
        print('✅ تم منع العداد من الرجوع لتاريخ الموعد القديم')
    s = s.replace("if(!start) return;", "if(!start) { el.textContent = 'وقت البدء غير مسجل'; return; }")
    view.write_text(s, encoding='utf-8')
else:
    print('⚠️ لم أجد صفحة مواعيد ProActive — تم إنشاء partial فقط')
PY

# تحسين ترتيب المواعيد + تحسين تغيير الحالة
python3 - <<'PY'
from pathlib import Path
p = Path('app/Http/Controllers/SuperAdmin/ProactiveScheduleController.php')
if not p.exists():
    print('⚠️ لم أجد ProactiveScheduleController.php')
    raise SystemExit(0)
s = p.read_text(encoding='utf-8')

# ترتيب ذكي: نشطة أولاً، ثم قادمة، ثم منتهية، ثم ملغاة — وداخلها أحدث تاريخ
old = """->orderBy('event_date','asc')
            ->orderBy('event_time','asc')"""
new = """->orderByRaw("CASE status WHEN 'active' THEN 0 WHEN 'upcoming' THEN 1 WHEN 'finished' THEN 2 WHEN 'cancelled' THEN 3 ELSE 9 END")
            ->orderBy('event_date','desc')
            ->orderByRaw("COALESCE(event_time,'00:00:00') DESC")"""
if old in s:
    s = s.replace(old, new, 1)
    print('✅ تم تعديل ترتيب المواعيد: نشطة أولاً ثم القادمة حسب آخر تاريخ')
elif "CASE status WHEN 'active'" in s:
    print('ℹ️ ترتيب المواعيد الذكي موجود مسبقًا')
else:
    print('⚠️ لم أستطع تعديل ترتيب المواعيد تلقائيًا — صيغة orderBy مختلفة')

# استبدال method setStatus بشكل آمن بالـ brace matching
start = s.find('public function setStatus(')
if start != -1:
    brace = s.find('{', start)
    if brace != -1:
        depth = 0
        end = None
        for i in range(brace, len(s)):
            if s[i] == '{':
                depth += 1
            elif s[i] == '}':
                depth -= 1
                if depth == 0:
                    end = i + 1
                    break
        if end:
            method = r'''public function setStatus($id, Request $request)
    {
        $status = $request->input('status');
        if (!in_array($status, ['upcoming','active','finished','cancelled'], true)) {
            return back()->with('error','حالة غير صالحة.');
        }

        $row = DB::table('proactive_schedules')->where('id', $id)->first();
        abort_unless($row, 404);

        $tz  = config('app.timezone', 'Asia/Jerusalem');
        $now = now($tz);

        $update = [
            'status' => $status,
            'updated_at' => $now,
        ];

        if ($status === 'active') {
            $update['started_at'] = $now;
            $update['finished_at'] = null;
            $update['duration_minutes'] = 0;
        } elseif ($status === 'finished') {
            $start = $row->started_at
                ? \Carbon\Carbon::parse($row->started_at, $tz)
                : $now->copy();

            $mins = (int) max(0, $start->diffInMinutes($now, false));

            $update['started_at'] = $row->started_at ?: $now;
            $update['finished_at'] = $now;
            $update['duration_minutes'] = $mins;
        } elseif ($status === 'upcoming') {
            $update['started_at'] = null;
            $update['finished_at'] = null;
            $update['duration_minutes'] = 0;
        } elseif ($status === 'cancelled') {
            $update['finished_at'] = $row->finished_at ?: $now;
            $update['duration_minutes'] = (int) ($row->duration_minutes ?? 0);
        }

        DB::table('proactive_schedules')->where('id', $id)->update($update);

        try {
            if (\Illuminate\Support\Facades\Schema::hasTable('proactive_schedule_status_logs')) {
                DB::table('proactive_schedule_status_logs')->insert([
                    'schedule_id' => $row->id,
                    'old_status' => $row->status ?: 'upcoming',
                    'new_status' => $status,
                    'changed_by' => auth()->id(),
                    'changed_at' => $now,
                    'note' => $status === 'finished' ? 'تم الإنهاء مع تذكير كتابة التقرير' : 'تغيير حالة من لوحة ProActive',
                    'delta_minutes' => (int) ($update['duration_minutes'] ?? 0),
                ]);
            }
        } catch (\Throwable $e) {
            // لا نكسر تغيير الحالة إذا سجل اللوج فشل
        }

        if ($status === 'finished') {
            $reportsUrl = url('/superadmin/proactive-reports');
            foreach ([
                'superadmin.proactive.reports.index',
                'superadmin.proactiveReports.index',
                'superadmin.proactive.reports',
                'superadmin.proactiveReports',
            ] as $routeName) {
                if (\Illuminate\Support\Facades\Route::has($routeName)) {
                    $reportsUrl = route($routeName);
                    break;
                }
            }

            return redirect()->to($reportsUrl)
                ->with('success', 'تم إنهاء فعالية ProActive ✅ الآن اكتب التقرير حتى لا تبقى ناقصة.');
        }

        return back()->with('success','تم تغيير الحالة.');
    }'''
            s = s[:start] + method + s[end:]
            print('✅ تم تحديث منطق تغيير الحالة وربطه بتذكير التقارير')
        else:
            print('⚠️ لم أستطع تحديد نهاية setStatus')
else:
    print('⚠️ لم أجد setStatus داخل الكنترول')

p.write_text(s, encoding='utf-8')
PY

# فحص syntax للكنترول
if [[ -f "$SCHEDULE_CONTROLLER" ]]; then
  php -l "$SCHEDULE_CONTROLLER" || {
    echo "❌ في خطأ PHP Syntax. أرجّع النسخة الاحتياطية من: $BACKUP_DIR" >&2
    exit 1
  }
fi

# تنظيف كاش Laravel
php artisan optimize:clear >/dev/null || true
php artisan view:clear >/dev/null || true
php artisan route:clear >/dev/null || true
php artisan config:clear >/dev/null || true

echo ""
echo "✅ تم تركيب باتش v5 بنجاح"
echo "━━━━━━━━━━━━━━━━━━━━"
echo "عملنا:" 
echo "• تذكير في الداشبورد بموعد ProActive اليوم"
echo "• فحص الفعاليات النشطة"
echo "• فحص المنتهية بدون تقارير آخر 14 يوم"
echo "• زر يودّي مباشرة لصفحة التقارير"
echo "• حارس داخل صفحة المواعيد"
echo "• ترتيب: نشطة أولاً، ثم القادمة، ثم حسب آخر تاريخ"
echo "• عند إنهاء فعالية يودّيك لصفحة التقارير"
echo "• منع عداد نشطة منذ من الرجوع لتاريخ الموعد القديم"
echo ""
echo "📦 Backup محفوظ هنا: $BACKUP_DIR"
