#!/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_v6_safe.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_v6_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 v6 SAFE..."
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_v6.blade.php <<'BLADE'
{{-- PROACTIVE_DASHBOARD_REMINDERS_PARTIAL_V6_SAFE --}}
@php
  $__pd = [
      'ready' => false,
      'today' => collect(),
      'active' => collect(),
      'stale' => collect(),
      'missing' => collect(),
      'cols' => [],
      'dateCol' => null,
      'timeCol' => null,
      'titleCol' => null,
      'statusCol' => null,
      'typeCol' => null,
      'platformCol' => null,
      'leaderCol' => null,
      'reportsUrl' => url('/superadmin/proactive-reports'),
      'schedulesUrl' => url('/superadmin/proactive/schedules'),
      'error' => null,
  ];

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

      foreach ([
          'superadmin.proactive.reports.index',
          'superadmin.proactiveReports.index',
          'superadmin.proactive.report.index',
          'superadmin.proactiveReports',
      ] as $__r) {
          if (\Illuminate\Support\Facades\Route::has($__r)) {
              $__pd['reportsUrl'] = route($__r);
              break;
          }
      }

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

      if (\Illuminate\Support\Facades\Schema::hasTable('proactive_schedules')) {
          $__cols = \Illuminate\Support\Facades\Schema::getColumnListing('proactive_schedules');
          $__pick = function(array $__names) use ($__cols) {
              foreach ($__names as $__name) {
                  if (in_array($__name, $__cols, true)) return $__name;
              }
              return null;
          };
          $__dateCol = $__pick(['event_date','activity_date','date','schedule_date','scheduled_date','start_date','day']);
          $__timeCol = $__pick(['event_time','activity_time','time','start_time','scheduled_time','hour']);
          $__titleCol = $__pick(['event_title','activity_title','title','name','subject']);
          $__statusCol = $__pick(['status','state']);
          $__typeCol = $__pick(['event_type','activity_type','type']);
          $__platformCol = $__pick(['platform','source','channel']);
          $__leaderCol = $__pick(['leader_name','leader','admin_name','owner_name','created_by_name']);

          $__pd['cols'] = $__cols;
          $__pd['dateCol'] = $__dateCol;
          $__pd['timeCol'] = $__timeCol;
          $__pd['titleCol'] = $__titleCol;
          $__pd['statusCol'] = $__statusCol;
          $__pd['typeCol'] = $__typeCol;
          $__pd['platformCol'] = $__platformCol;
          $__pd['leaderCol'] = $__leaderCol;

          if ($__dateCol) {
              $__todayQ = \Illuminate\Support\Facades\DB::table('proactive_schedules')
                  ->whereDate($__dateCol, $__today);
              if ($__statusCol) {
                  $__todayQ->whereIn($__statusCol, ['upcoming','active','finished']);
                  $__todayQ->orderByRaw("CASE {$__statusCol} WHEN 'active' THEN 0 WHEN 'upcoming' THEN 1 WHEN 'finished' THEN 2 WHEN 'cancelled' THEN 3 ELSE 9 END");
              }
              if ($__timeCol) $__todayQ->orderByRaw("COALESCE({$__timeCol}, '00:00:00') ASC");
              $__pd['today'] = $__todayQ->limit(6)->get();
          }

          if ($__statusCol) {
              $__activeQ = \Illuminate\Support\Facades\DB::table('proactive_schedules')
                  ->where($__statusCol, 'active');
              if ($__dateCol) $__activeQ->orderBy($__dateCol, 'desc');
              if ($__timeCol) $__activeQ->orderByRaw("COALESCE({$__timeCol}, '00:00:00') DESC");
              $__pd['active'] = $__activeQ->limit(6)->get();

              if ($__dateCol) {
                  $__pd['stale'] = \Illuminate\Support\Facades\DB::table('proactive_schedules')
                      ->where($__statusCol, 'active')
                      ->whereDate($__dateCol, '<', $__today)
                      ->orderBy($__dateCol, 'desc')
                      ->limit(6)
                      ->get();
              }
          }

          if ($__dateCol && $__statusCol && \Illuminate\Support\Facades\Schema::hasTable('proactive_reports')) {
              $__rcols = \Illuminate\Support\Facades\Schema::getColumnListing('proactive_reports');
              $__rpick = function(array $__names) use ($__rcols) {
                  foreach ($__names as $__name) {
                      if (in_array($__name, $__rcols, true)) return $__name;
                  }
                  return null;
              };
              $__reportDateCol = $__rpick(['activity_date','event_date','report_date','date','created_at']);
              $__reportTypeCol = $__rpick(['activity_type','event_type','type']);
              $__reportPlatformCol = $__rpick(['platform','source','channel']);

              if ($__reportDateCol) {
                  $__missingQ = \Illuminate\Support\Facades\DB::table('proactive_schedules as s')
                      ->where('s.'.$__statusCol, 'finished')
                      ->whereDate('s.'.$__dateCol, '>=', $__from)
                      ->whereDate('s.'.$__dateCol, '<=', $__today)
                      ->whereNotExists(function($__q) use ($__reportDateCol, $__dateCol, $__reportTypeCol, $__typeCol, $__reportPlatformCol, $__platformCol) {
                          $__q->select(\Illuminate\Support\Facades\DB::raw(1))
                              ->from('proactive_reports as r')
                              ->whereColumn('r.'.$__reportDateCol, 's.'.$__dateCol);
                          if ($__reportTypeCol && $__typeCol) {
                              $__q->whereColumn('r.'.$__reportTypeCol, 's.'.$__typeCol);
                          }
                          if ($__reportPlatformCol && $__platformCol) {
                              $__q->whereColumn('r.'.$__reportPlatformCol, 's.'.$__platformCol);
                          }
                      })
                      ->orderBy('s.'.$__dateCol, 'desc');
                  if ($__timeCol) $__missingQ->orderByRaw("COALESCE(s.{$__timeCol}, '00:00:00') DESC");
                  $__pd['missing'] = $__missingQ->limit(6)->get();
              }
          }

          $__pd['ready'] = true;
      }
  } catch (\Throwable $__e) {
      $__pd['ready'] = false;
      $__pd['error'] = $__e->getMessage();
  }

  $__val = function($__row, $__col, $__default = '') {
      if (!$__col || !$__row) return $__default;
      return isset($__row->{$__col}) ? $__row->{$__col} : $__default;
  };

  $__show = $__pd['ready'] && ($__pd['today']->count() || $__pd['active']->count() || $__pd['stale']->count() || $__pd['missing']->count());
@endphp

@if($__show)
  <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">{{ $__pd['today']->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">{{ $__pd['active']->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">{{ $__pd['stale']->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">{{ $__pd['missing']->count() }}</div>
            </div>
          </div>

          <div class="space-y-2 text-[12px] text-white/80">
            @if($__pd['today']->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($__pd['today'] 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">
                    {{ $__val($__r, $__pd['timeCol'], 'بدون وقت') }} — {{ $__val($__r, $__pd['titleCol'], 'ProActive') }}
                  </span>
                @endforeach
              </div>
            @endif

            @if($__pd['active']->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($__pd['stale']->count())
              <div class="rounded-2xl border border-amber-300/15 bg-amber-400/5 px-3 py-2">
                <b class="text-amber-100">تنبيه وقت:</b>
                في فعالية نشطة لكن تاريخها قديم. افتح المواعيد وصحّحها.
              </div>
            @endif

            @if($__pd['missing']->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="{{ $__pd['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="{{ $__pd['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_v6.blade.php <<'BLADE'
{{-- PROACTIVE_SCHEDULE_SMART_REMINDERS_PARTIAL_V6_SAFE --}}
@includeIf('superadmin.partials.proactive_dashboard_reminders_v6')
BLADE

python3 - <<'PY'
from pathlib import Path

def remove_block(s, start_marker, end_marker):
    while start_marker in s and end_marker in s:
        a = s.find(start_marker)
        b = s.find(end_marker, a)
        if a == -1 or b == -1:
            break
        b = b + len(end_marker)
        s = s[:a] + s[b:]
    return s

# 1) تنظيف حقن v5/v6 القديم من layout ثم حقن v6 بطريقة Blade صحيحة
layout = Path('resources/views/layouts/superadmin.blade.php')
if layout.exists():
    s = layout.read_text(encoding='utf-8')
    s = remove_block(s, '{{-- PROACTIVE_DASHBOARD_REMINDERS_V5 --}}', '{{-- /PROACTIVE_DASHBOARD_REMINDERS_V5 --}}')
    s = remove_block(s, '{{-- PROACTIVE_DASHBOARD_REMINDERS_V6 --}}', '{{-- /PROACTIVE_DASHBOARD_REMINDERS_V6 --}}')

    block = """{{-- PROACTIVE_DASHBOARD_REMINDERS_V6 --}}
@php
  $__proactiveDashPathV6 = trim(request()->path(), '/');
  $__isProactiveDashV6 = request()->routeIs('superadmin.dashboard') || request()->routeIs('dashboard') || in_array($__proactiveDashPathV6, ['superadmin','superadmin/dashboard','dashboard'], true);
@endphp
@if($__isProactiveDashV6)
  @includeIf('superadmin.partials.proactive_dashboard_reminders_v6')
@endif
{{-- /PROACTIVE_DASHBOARD_REMINDERS_V6 --}}
"""
    if '{{-- PROACTIVE_DASHBOARD_REMINDERS_V6 --}}' not in s:
        inserted = False
        for token in ["@yield('content')", '@yield("content")']:
            if token in s:
                s = s.replace(token, block + "\n" + token, 1)
                inserted = True
                break
        if not inserted:
            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('✅ تم تركيب تنبيه الداشبورد v6 بطريقة آمنة')
else:
    print('⚠️ لم أجد layout: resources/views/layouts/superadmin.blade.php')

# 2) حقن حارس صفحة المواعيد + إصلاح عداد active
view = Path('resources/views/superadmin/proactive/schedules/index.blade.php')
if view.exists():
    s = view.read_text(encoding='utf-8')
    s = remove_block(s, '{{-- PROACTIVE_SCHEDULE_SMART_REMINDERS_V5 --}}', '{{-- /PROACTIVE_SCHEDULE_SMART_REMINDERS_V5 --}}')
    s = remove_block(s, '{{-- PROACTIVE_SCHEDULE_SMART_REMINDERS_V6 --}}', '{{-- /PROACTIVE_SCHEDULE_SMART_REMINDERS_V6 --}}')

    block = """{{-- PROACTIVE_SCHEDULE_SMART_REMINDERS_V6 --}}
@includeIf('superadmin.proactive.schedules._smart_reminders_v6')
{{-- /PROACTIVE_SCHEDULE_SMART_REMINDERS_V6 --}}
"""
    if '{{-- PROACTIVE_SCHEDULE_SMART_REMINDERS_V6 --}}' not in s:
        if '{{-- ✅ STATS CARDS' in s:
            s = s.replace('{{-- ✅ STATS CARDS', block + '\n{{-- ✅ STATS CARDS', 1)
        elif '{{-- ✅ FLASH --}}' in s:
            s = s.replace('{{-- ✅ FLASH --}}', '{{-- ✅ FLASH --}}\n' + block, 1)
        else:
            s = s.replace("@section('content')", "@section('content')\n" + block, 1)

    # منع العداد من استخدام event_date كبديل إذا started_at فاضي
    s = s.replace("data-start=\"{{ $item->started_at ?? ($item->event_date.' '.($item->event_time ?? '00:00:00')) }}\"", "data-start=\"{{ $item->started_at }}\"")
    s = s.replace("if(!start) return;", "if(!start) { el.textContent = 'وقت البدء غير مسجل'; return; }")

    view.write_text(s, encoding='utf-8')
    print('✅ تم تركيب حارس صفحة المواعيد v6 + إصلاح العداد')
else:
    print('⚠️ لم أجد صفحة المواعيد: resources/views/superadmin/proactive/schedules/index.blade.php')
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 مختلفة')

# استبدال setStatus فقط إذا موجودة
start = s.find('public function setStatus(')
if start != -1:
    brace = s.find('{', start)
    end = None
    if brace != -1:
        depth = 0
        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);

        try {
            $cols = \Illuminate\Support\Facades\Schema::getColumnListing('proactive_schedules');
        } catch (\Throwable $e) {
            $cols = [];
        }

        $update = ['status' => $status, 'updated_at' => $now];
        $put = function($column, $value) use (&$update, $cols) {
            if (in_array($column, $cols, true)) {
                $update[$column] = $value;
            }
        };

        if ($status === 'active') {
            $put('started_at', $now);
            $put('finished_at', null);
            $put('duration_minutes', 0);
        } elseif ($status === 'finished') {
            $startAt = !empty($row->started_at) ? \Carbon\Carbon::parse($row->started_at, $tz) : $now->copy();
            $mins = (int) max(0, $startAt->diffInMinutes($now, false));
            $put('started_at', !empty($row->started_at) ? $row->started_at : $now);
            $put('finished_at', $now);
            $put('duration_minutes', $mins);
        } elseif ($status === 'upcoming') {
            $put('started_at', null);
            $put('finished_at', null);
            $put('duration_minutes', 0);
        } elseif ($status === 'cancelled') {
            $put('finished_at', !empty($row->finished_at) ? $row->finished_at : $now);
            $put('duration_minutes', (int)($row->duration_minutes ?? 0));
        }

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

        if ($status === 'finished') {
            $reportsUrl = url('/superadmin/proactive-reports');
            foreach ([
                'superadmin.proactive.reports.index',
                'superadmin.proactiveReports.index',
                'superadmin.proactive.report.index',
                '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('✅ تم تحديث setStatus: بدء/إنهاء مضبوط + تحويل للتقارير عند الإنهاء')
    else:
        print('⚠️ لم أستطع تحديد نهاية setStatus')
else:
    print('⚠️ لم أجد setStatus داخل الكنترول')

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

if [[ -f "$SCHEDULE_CONTROLLER" ]]; then
  echo "🔎 فحص Syntax للكنترول..."
  php -l "$SCHEDULE_CONTROLLER"
fi

echo "🧹 تنظيف كاش 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

cat <<EOF

✅ تم تركيب v6 SAFE بنجاح
━━━━━━━━━━━━━━━━━━━━
اللي تركّب:
• تذكير ProActive بالداشبورد إذا في موعد اليوم
• فحص فعالية نشطة الآن
• فحص نشطة بتاريخ قديم
• فحص منتهية بلا تقرير آخر 14 يوم
• زر يودّي لصفحة التقارير
• حارس داخل صفحة مواعيد ProActive
• ترتيب: النشطة أولاً ثم القادمة ثم الأحدث
• عند الضغط إنهِ الآن يودّي لصفحة التقارير
• العداد ما يرجع يحسب من تاريخ الموعد القديم إذا started_at فاضي

📦 Backup محفوظ هنا:
$BACKUP_DIR

ملاحظة:
خطأ route:list عندك بسبب AcademyCoursesController مفقود، وهذا خارج ProActive.
EOF
