<?php
// ============================================================
// modules/admin/reports.php — التقارير
// ============================================================
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/rbac.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/layout.php';
require_once __DIR__ . '/../../includes/sidebar_helper.php';

requireLogin(); requireRole(ROLE_ADMIN);
$GLOBALS['BASE_URL_CSS'] = BASE_URL . '/public/assets/css/main.css';
$user = currentUser(); $pdo = db();

// ── الفلتر الزمني ────────────────────────────────────────────
$from = $_GET['from'] ?? date('Y-m-d', strtotime('-12 months'));
$to   = $_GET['to']   ?? date('Y-m-d');
$dateFilter = "AND DATE(c.filing_date) BETWEEN ? AND ?";
$dateParams = [$from, $to];

// ── دالة مساعدة: تنفيذ استعلام مع باراميترات ────────────────
$fetchCount = function($sql, $params = []) use ($pdo) {
    $s = $pdo->prepare($sql);
    $s->execute($params);
    return (int)$s->fetchColumn();
};
$fetchAll = function($sql, $params = []) use ($pdo) {
    $s = $pdo->prepare($sql);
    $s->execute($params);
    return $s->fetchAll();
};

// ============================================================
// KPI: المؤشرات الرئيسية
// ============================================================
$totalCases     = $fetchCount("SELECT COUNT(*) FROM cases c WHERE 1=1 $dateFilter", $dateParams);
$openCases      = $fetchCount("SELECT COUNT(*) FROM cases c WHERE c.status='open' $dateFilter", $dateParams);
$closedCases    = $fetchCount("SELECT COUNT(*) FROM cases c WHERE c.status='closed' $dateFilter", $dateParams);
$totalSessions  = $fetchCount("SELECT COUNT(*) FROM sessions s JOIN cases c ON s.case_id=c.id WHERE 1=1 $dateFilter", $dateParams);
$totalJudgments = $fetchCount("SELECT COUNT(*) FROM judgments j JOIN cases c ON j.case_id=c.id WHERE 1=1 $dateFilter", $dateParams);
$totalAppeals   = $fetchCount("SELECT COUNT(*) FROM appeals a JOIN cases c ON a.case_id=c.id WHERE 1=1 $dateFilter", $dateParams);

// ============================================================
// 1) القضايا حسب الحالة
// ============================================================
$byStatus = $fetchAll("
    SELECT c.status, COUNT(*) AS cnt
    FROM cases c WHERE 1=1 $dateFilter
    GROUP BY c.status ORDER BY cnt DESC
", $dateParams);

// ============================================================
// 2) القضايا حسب فرع القضاء
// ============================================================
$byBranch = $fetchAll("
    SELECT c.court_branch, COUNT(*) AS cnt
    FROM cases c WHERE 1=1 $dateFilter
    GROUP BY c.court_branch
", $dateParams);

// ============================================================
// 3) القضايا حسب النوع
// ============================================================
$byType = $fetchAll("
    SELECT c.case_type, COUNT(*) AS cnt
    FROM cases c WHERE 1=1 $dateFilter
    GROUP BY c.case_type ORDER BY cnt DESC
", $dateParams);

// ============================================================
// 4) الأحكام: غيابية vs حضورية
// ============================================================
$judgmentBreakdown = $fetchAll("
    SELECT j.is_default, COUNT(*) AS cnt
    FROM judgments j JOIN cases c ON j.case_id=c.id
    WHERE 1=1 $dateFilter
    GROUP BY j.is_default
", $dateParams);
$defaultJudgments      = 0;
$adversarialJudgments  = 0;
foreach ($judgmentBreakdown as $row) {
    if ((int)$row['is_default'] === 1) $defaultJudgments = (int)$row['cnt'];
    else $adversarialJudgments = (int)$row['cnt'];
}

// ============================================================
// 5) الطعون حسب النوع (يشمل المعارضة)
// ============================================================
$appealsByType = $fetchAll("
    SELECT a.appeal_type, COUNT(*) AS cnt
    FROM appeals a JOIN cases c ON a.case_id=c.id
    WHERE 1=1 $dateFilter
    GROUP BY a.appeal_type ORDER BY cnt DESC
", $dateParams);

// ============================================================
// 6) أكثر المحاكم استقبالاً للقضايا (Top 8)
// ============================================================
$topCourts = $fetchAll("
    SELECT ct.name AS court_name, ct.branch, ct.level, ct.wilaya_code, COUNT(c.id) AS cnt
    FROM cases c JOIN courts ct ON c.court_id=ct.id
    WHERE 1=1 $dateFilter
    GROUP BY ct.id ORDER BY cnt DESC LIMIT 8
", $dateParams);

// ============================================================
// 7) أكثر المحامين نشاطاً (Top 8)
// ============================================================
$topLawyers = $fetchAll("
    SELECT u.full_name, u.email, COUNT(cl.case_id) AS cnt
    FROM users u
    JOIN case_lawyers cl ON cl.lawyer_id=u.id
    JOIN cases c ON cl.case_id=c.id
    WHERE u.role='lawyer' $dateFilter
    GROUP BY u.id ORDER BY cnt DESC LIMIT 8
", $dateParams);

// ============================================================
// 8) القضايا الجديدة شهرياً (آخر 12 شهراً)
// ============================================================
$monthly = $fetchAll("
    SELECT DATE_FORMAT(c.filing_date, '%Y-%m') AS m, COUNT(*) AS cnt
    FROM cases c WHERE 1=1 $dateFilter
    GROUP BY m ORDER BY m ASC
", $dateParams);

// ============================================================
// 9) المحامون حسب حالة المراجعة
// ============================================================
$lawyerStatus = $fetchAll("
    SELECT lp.review_status, COUNT(*) AS cnt
    FROM lawyer_profiles lp
    GROUP BY lp.review_status
");

// ── خرائط الترجمة ────────────────────────────────────────────
$statusLabels = [];
foreach (CASE_STATUS as $k => $v) $statusLabels[$k] = $v['label'];
$reviewLabels = [
    'pending'      => 'في الانتظار',
    'under_review' => 'قيد المراجعة',
    'approved'     => 'مقبول',
    'rejected'     => 'مرفوض',
];

$notifCount = getUnreadNotifCount($user['id']);
renderHead('التقارير');
?>
<div class="sidebar" id="sidebar"><?php buildSidebar('reports','admin'); ?></div>
<div class="sidebar-overlay" id="sidebarOverlay"></div>
<div class="main-wrap">
<?php renderTopbar('التقارير الإحصائية', $notifCount); ?>
<div class="page-content">

  <!-- Filter bar -->
  <div class="panel mb-3">
    <div class="panel-body">
      <form method="GET" class="row g-2 align-items-end">
        <div class="col-md-3">
          <label class="form-label" style="font-size:12px">من تاريخ</label>
          <input type="date" name="from" class="form-control form-control-sm" value="<?= htmlspecialchars($from) ?>">
        </div>
        <div class="col-md-3">
          <label class="form-label" style="font-size:12px">إلى تاريخ</label>
          <input type="date" name="to" class="form-control form-control-sm" value="<?= htmlspecialchars($to) ?>">
        </div>
        <div class="col-md-3">
          <button class="btn btn-sm btn-gold"><i class="bi bi-funnel"></i> تطبيق</button>
          <a href="reports.php" class="btn btn-sm btn-outline-secondary"><i class="bi bi-arrow-counterclockwise"></i> آخر 12 شهراً</a>
        </div>
        <div class="col-md-3 text-md-end">
          <small class="text-muted">
            النطاق: <strong><?= htmlspecialchars($from) ?></strong> ← <strong><?= htmlspecialchars($to) ?></strong>
          </small>
        </div>
      </form>
    </div>
  </div>

  <!-- KPIs -->
  <div class="row g-3 mb-4">
    <div class="col-6 col-xl-2">
      <div class="stat-card"><div class="stat-icon navy"><i class="bi bi-folder2-open"></i></div>
        <div class="stat-body"><div class="stat-value"><?= number_format($totalCases) ?></div>
        <div class="stat-label">إجمالي القضايا</div></div></div>
    </div>
    <div class="col-6 col-xl-2">
      <div class="stat-card"><div class="stat-icon green"><i class="bi bi-folder-check"></i></div>
        <div class="stat-body"><div class="stat-value"><?= number_format($openCases) ?></div>
        <div class="stat-label">قضايا مفتوحة</div></div></div>
    </div>
    <div class="col-6 col-xl-2">
      <div class="stat-card"><div class="stat-icon gold"><i class="bi bi-archive"></i></div>
        <div class="stat-body"><div class="stat-value"><?= number_format($closedCases) ?></div>
        <div class="stat-label">قضايا مغلقة</div></div></div>
    </div>
    <div class="col-6 col-xl-2">
      <div class="stat-card"><div class="stat-icon navy"><i class="bi bi-calendar3"></i></div>
        <div class="stat-body"><div class="stat-value"><?= number_format($totalSessions) ?></div>
        <div class="stat-label">الجلسات</div></div></div>
    </div>
    <div class="col-6 col-xl-2">
      <div class="stat-card"><div class="stat-icon gold"><i class="bi bi-award"></i></div>
        <div class="stat-body"><div class="stat-value"><?= number_format($totalJudgments) ?></div>
        <div class="stat-label">الأحكام</div></div></div>
    </div>
    <div class="col-6 col-xl-2">
      <div class="stat-card"><div class="stat-icon red"><i class="bi bi-arrow-repeat"></i></div>
        <div class="stat-body"><div class="stat-value"><?= number_format($totalAppeals) ?></div>
        <div class="stat-label">الطعون</div></div></div>
    </div>
  </div>

  <!-- Monthly trend chart -->
  <div class="panel mb-3">
    <div class="panel-header">
      <div class="panel-title"><i class="bi bi-graph-up"></i> منحنى القضايا الجديدة شهرياً</div>
    </div>
    <div class="panel-body">
      <?php if (empty($monthly)): ?>
        <div class="text-center text-muted py-4">لا توجد بيانات في النطاق المحدد</div>
      <?php else: ?>
        <canvas id="monthlyChart" height="80"></canvas>
      <?php endif; ?>
    </div>
  </div>

  <div class="row g-3 mb-3">
    <!-- Cases by status -->
    <div class="col-lg-4">
      <div class="panel">
        <div class="panel-header"><div class="panel-title"><i class="bi bi-pie-chart"></i> القضايا حسب الحالة</div></div>
        <div class="panel-body">
          <?php if (empty($byStatus)): ?>
            <div class="text-center text-muted py-3">لا توجد بيانات</div>
          <?php else: foreach ($byStatus as $row):
              $pct = $totalCases ? round(($row['cnt'] / $totalCases) * 100, 1) : 0;
              $cls = CASE_STATUS[$row['status']]['class'] ?? 'secondary';
              $lbl = CASE_STATUS[$row['status']]['label'] ?? $row['status'];
          ?>
          <div class="mb-2">
            <div class="d-flex justify-content-between" style="font-size:13px">
              <span><?= htmlspecialchars($lbl) ?></span>
              <strong><?= number_format($row['cnt']) ?> (<?= $pct ?>%)</strong>
            </div>
            <div class="progress" style="height:8px">
              <div class="progress-bar bg-<?= $cls ?>" style="width:<?= $pct ?>%"></div>
            </div>
          </div>
          <?php endforeach; endif; ?>
        </div>
      </div>
    </div>

    <!-- Cases by branch -->
    <div class="col-lg-4">
      <div class="panel">
        <div class="panel-header"><div class="panel-title"><i class="bi bi-bank2"></i> القضايا حسب فرع القضاء</div></div>
        <div class="panel-body">
          <?php if (empty($byBranch)): ?>
            <div class="text-center text-muted py-3">لا توجد بيانات</div>
          <?php else:
            $branchColors = ['ordinary'=>'navy','administrative'=>'gold'];
            foreach ($byBranch as $row):
              $pct = $totalCases ? round(($row['cnt'] / $totalCases) * 100, 1) : 0;
              $cls = $branchColors[$row['court_branch']] ?? 'secondary';
              $lbl = COURT_BRANCHES[$row['court_branch']] ?? $row['court_branch'];
          ?>
          <div class="mb-3">
            <div class="d-flex justify-content-between" style="font-size:13px">
              <span><?= htmlspecialchars($lbl) ?></span>
              <strong><?= number_format($row['cnt']) ?> (<?= $pct ?>%)</strong>
            </div>
            <div class="progress" style="height:8px">
              <div class="progress-bar bg-<?= $cls ?>" style="width:<?= $pct ?>%"></div>
            </div>
          </div>
          <?php endforeach; endif; ?>
        </div>
      </div>
    </div>

    <!-- Cases by type -->
    <div class="col-lg-4">
      <div class="panel">
        <div class="panel-header"><div class="panel-title"><i class="bi bi-tags"></i> القضايا حسب النوع</div></div>
        <div class="panel-body">
          <?php if (empty($byType)): ?>
            <div class="text-center text-muted py-3">لا توجد بيانات</div>
          <?php else: foreach ($byType as $row):
              $pct = $totalCases ? round(($row['cnt'] / $totalCases) * 100, 1) : 0;
              $lbl = CASE_TYPES[$row['case_type']] ?? $row['case_type'];
          ?>
          <div class="mb-2">
            <div class="d-flex justify-content-between" style="font-size:13px">
              <span><?= htmlspecialchars($lbl) ?></span>
              <strong><?= number_format($row['cnt']) ?> (<?= $pct ?>%)</strong>
            </div>
            <div class="progress" style="height:8px">
              <div class="progress-bar bg-gold" style="width:<?= $pct ?>%"></div>
            </div>
          </div>
          <?php endforeach; endif; ?>
        </div>
      </div>
    </div>
  </div>

  <div class="row g-3 mb-3">
    <!-- Judgment breakdown -->
    <div class="col-lg-4">
      <div class="panel h-100">
        <div class="panel-header"><div class="panel-title"><i class="bi bi-award"></i> الأحكام: غيابية vs حضورية</div></div>
        <div class="panel-body">
          <?php $totalJ = $defaultJudgments + $adversarialJudgments;
                $pctD = $totalJ ? round(($defaultJudgments/$totalJ)*100,1) : 0;
                $pctA = $totalJ ? round(($adversarialJudgments/$totalJ)*100,1) : 0; ?>
          <div class="mb-3">
            <div class="d-flex justify-content-between" style="font-size:13px">
              <span><i class="bi bi-person-x text-info"></i> غيابية</span>
              <strong><?= number_format($defaultJudgments) ?> (<?= $pctD ?>%)</strong>
            </div>
            <div class="progress" style="height:10px">
              <div class="progress-bar bg-info" style="width:<?= $pctD ?>%"></div>
            </div>
          </div>
          <div class="mb-3">
            <div class="d-flex justify-content-between" style="font-size:13px">
              <span><i class="bi bi-person-check text-success"></i> حضورية</span>
              <strong><?= number_format($adversarialJudgments) ?> (<?= $pctA ?>%)</strong>
            </div>
            <div class="progress" style="height:10px">
              <div class="progress-bar bg-success" style="width:<?= $pctA ?>%"></div>
            </div>
          </div>
          <small class="text-muted" style="font-size:11px">
            الأحكام الغيابية وحدها قابلة للمعارضة.
          </small>
        </div>
      </div>
    </div>

    <!-- Appeals by type -->
    <div class="col-lg-4">
      <div class="panel h-100">
        <div class="panel-header"><div class="panel-title"><i class="bi bi-arrow-repeat"></i> الطعون حسب النوع</div></div>
        <div class="panel-body">
          <?php if (empty($appealsByType)): ?>
            <div class="text-center text-muted py-3">لا توجد طعون في النطاق المحدد</div>
          <?php else: foreach ($appealsByType as $row):
              $pct = $totalAppeals ? round(($row['cnt'] / $totalAppeals) * 100, 1) : 0;
              $meta = RECOURSE_TYPES[$row['appeal_type']] ?? ['label'=>$row['appeal_type'],'class'=>'secondary'];
          ?>
          <div class="mb-2">
            <div class="d-flex justify-content-between" style="font-size:13px">
              <span><?= htmlspecialchars($meta['label']) ?></span>
              <strong><?= number_format($row['cnt']) ?> (<?= $pct ?>%)</strong>
            </div>
            <div class="progress" style="height:8px">
              <div class="progress-bar bg-<?= $meta['class'] ?>" style="width:<?= $pct ?>%"></div>
            </div>
          </div>
          <?php endforeach; endif; ?>
        </div>
      </div>
    </div>

    <!-- Lawyer review status -->
    <div class="col-lg-4">
      <div class="panel h-100">
        <div class="panel-header"><div class="panel-title"><i class="bi bi-person-vcard"></i> ملفات المحامين</div></div>
        <div class="panel-body">
          <?php if (empty($lawyerStatus)): ?>
            <div class="text-center text-muted py-3">لا توجد ملفات محامين</div>
          <?php else:
            $totalLp = array_sum(array_column($lawyerStatus, 'cnt'));
            $rsColors = ['pending'=>'warning','under_review'=>'info','approved'=>'success','rejected'=>'danger'];
            foreach ($lawyerStatus as $row):
              $pct = $totalLp ? round(($row['cnt'] / $totalLp) * 100, 1) : 0;
              $cls = $rsColors[$row['review_status']] ?? 'secondary';
              $lbl = $reviewLabels[$row['review_status']] ?? $row['review_status'];
          ?>
          <div class="mb-2">
            <div class="d-flex justify-content-between" style="font-size:13px">
              <span><?= htmlspecialchars($lbl) ?></span>
              <strong><?= number_format($row['cnt']) ?> (<?= $pct ?>%)</strong>
            </div>
            <div class="progress" style="height:8px">
              <div class="progress-bar bg-<?= $cls ?>" style="width:<?= $pct ?>%"></div>
            </div>
          </div>
          <?php endforeach; endif; ?>
        </div>
      </div>
    </div>
  </div>

  <div class="row g-3">
    <!-- Top courts -->
    <div class="col-lg-6">
      <div class="panel">
        <div class="panel-header"><div class="panel-title"><i class="bi bi-trophy"></i> أكثر المحاكم استقبالاً للقضايا</div></div>
        <?php if (empty($topCourts)): ?>
          <div class="empty-state py-4 text-center">
            <i class="bi bi-bank2" style="font-size:36px;color:var(--text-muted)"></i>
            <p class="mt-2 text-muted">لا توجد قضايا مُسندة لمحاكم بعد</p>
          </div>
        <?php else: ?>
        <div class="table-responsive">
          <table class="table mb-0">
            <thead><tr><th>#</th><th>المحكمة</th><th>الفرع</th><th>الولاية</th><th>عدد القضايا</th></tr></thead>
            <tbody>
            <?php foreach ($topCourts as $i => $row): ?>
            <tr>
              <td class="text-muted" style="font-size:12px"><?= $i+1 ?></td>
              <td style="font-size:13px;font-weight:600"><?= htmlspecialchars($row['court_name']) ?></td>
              <td><span class="badge bg-<?= $row['branch']==='ordinary'?'navy':'gold' ?>" style="font-size:11px">
                <?= COURT_BRANCHES[$row['branch']] ?? '' ?>
              </span></td>
              <td style="font-size:12px"><?= WILAYAS[$row['wilaya_code']] ?? '—' ?></td>
              <td><strong class="text-gold"><?= number_format($row['cnt']) ?></strong></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Top lawyers -->
    <div class="col-lg-6">
      <div class="panel">
        <div class="panel-header"><div class="panel-title"><i class="bi bi-person-badge"></i> أكثر المحامين نشاطاً</div></div>
        <?php if (empty($topLawyers)): ?>
          <div class="empty-state py-4 text-center">
            <i class="bi bi-person-badge" style="font-size:36px;color:var(--text-muted)"></i>
            <p class="mt-2 text-muted">لا توجد قضايا مُسندة لمحامين بعد</p>
          </div>
        <?php else: ?>
        <div class="table-responsive">
          <table class="table mb-0">
            <thead><tr><th>#</th><th>المحامي</th><th>البريد</th><th>عدد القضايا</th></tr></thead>
            <tbody>
            <?php foreach ($topLawyers as $i => $row): ?>
            <tr>
              <td class="text-muted" style="font-size:12px"><?= $i+1 ?></td>
              <td style="font-size:13px;font-weight:600"><?= htmlspecialchars($row['full_name']) ?></td>
              <td style="font-size:12px;color:var(--text-muted)"><?= htmlspecialchars($row['email']) ?></td>
              <td><strong class="text-gold"><?= number_format($row['cnt']) ?></strong></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        <?php endif; ?>
      </div>
    </div>
  </div>

</div></div>

<?php if (!empty($monthly)): ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
const monthlyData = <?= json_encode($monthly, JSON_UNESCAPED_UNICODE) ?>;
const ctx = document.getElementById('monthlyChart');
if (ctx && typeof Chart !== 'undefined') {
  new Chart(ctx, {
    type: 'line',
    data: {
      labels: monthlyData.map(r => r.m),
      datasets: [{
        label: 'عدد القضايا',
        data: monthlyData.map(r => parseInt(r.cnt)),
        borderColor: '#c9a84c',
        backgroundColor: 'rgba(201,168,76,0.12)',
        borderWidth: 2,
        tension: 0.3,
        fill: true,
        pointBackgroundColor: '#0a1628',
        pointRadius: 4
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: true,
      plugins: { legend: { display: false } },
      scales: {
        y: { beginAtZero: true, ticks: { precision: 0 } }
      }
    }
  });
}
</script>
<?php endif; ?>
<?php renderFoot(); ?>
