<?php
date_default_timezone_set('Asia/Dubai');

require_once 'db.php';
require_once 'inc/layout.php';

$pdo = db();

if (!$pdo instanceof PDO) {
    http_response_code(500);
    exit('DB not ready');
}

$canDeleteLogs = in_array(
    strtoupper((string)current_role()),
    ['OWNER', 'ADMIN', 'SUPER_ADMIN'],
    true
);

$q = trim((string)($_GET['q'] ?? ''));

/* حذف سجل */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_log_id'])) {
    if (!$canDeleteLogs) {
        die('غير مصرح');
    }

    $id = (int)$_POST['delete_log_id'];

    if ($id > 0) {
        $st = $pdo->prepare("DELETE FROM system_activity_logs WHERE id = ? LIMIT 1");
        $st->execute([$id]);
    }

    $back = 'activity_logs.php';
    if (!empty($_POST['current_q'])) {
        $back .= '?q=' . urlencode((string)$_POST['current_q']);
    }

    header("Location: " . $back);
    exit;
}

/* البحث الذكي */
$where  = '';
$params = [];

if ($q !== '') {
    $where = "
        WHERE (
            l.title LIKE ?
            OR l.description LIKE ?
            OR l.module LIKE ?
            OR l.action_type LIKE ?
            OR l.created_at LIKE ?
            OR e.full_name LIKE ?
            OR e.name LIKE ?
            OR u.name LIKE ?
            OR u.username LIKE ?
        )
    ";

    $like = '%' . $q . '%';
    $params = array_fill(0, 9, $like);
}

/* السجلات */
$stLogs = $pdo->prepare("
    SELECT 
        l.*,
        COALESCE(
            NULLIF(e.full_name, ''),
            NULLIF(e.name, ''),
            NULLIF(u.name, ''),
            NULLIF(u.username, ''),
            CONCAT('مستخدم #', l.user_id)
        ) AS employee_name
    FROM system_activity_logs l
    LEFT JOIN employees e ON e.id = l.employee_id
    LEFT JOIN users u ON u.id = l.user_id
    $where
    ORDER BY l.id DESC
    LIMIT 100
");

$stLogs->execute($params);
$logs = $stLogs->fetchAll(PDO::FETCH_ASSOC);

/* إحصائيات الموظفين */
$employeeStats = $pdo->query("
    SELECT
        COALESCE(
            NULLIF(e.full_name, ''),
            NULLIF(e.name, ''),
            NULLIF(u.name, ''),
            NULLIF(u.username, ''),
            CONCAT('مستخدم #', l.user_id)
        ) AS employee_name,

        COUNT(*) AS total_actions,

        SUM(CASE WHEN l.action_type LIKE 'create_%' THEN 1 ELSE 0 END) AS created_count,
        SUM(CASE WHEN l.action_type LIKE 'update_%' THEN 1 ELSE 0 END) AS updated_count,
        SUM(CASE WHEN l.action_type LIKE 'delete_%' THEN 1 ELSE 0 END) AS deleted_count,
        SUM(CASE WHEN l.module = 'clients' THEN 1 ELSE 0 END) AS clients_count,
        SUM(CASE WHEN l.module = 'tasks' THEN 1 ELSE 0 END) AS tasks_count,
        SUM(CASE WHEN l.module = 'cases' THEN 1 ELSE 0 END) AS cases_count

    FROM system_activity_logs l
    LEFT JOIN employees e ON e.id = l.employee_id
    LEFT JOIN users u ON u.id = l.user_id
    GROUP BY employee_name
    ORDER BY total_actions DESC
    LIMIT 8
")->fetchAll(PDO::FETCH_ASSOC);

function get_employee_status(array $s): array
{
    $total   = (int)($s['total_actions'] ?? 0);
    $tasks   = (int)($s['tasks_count'] ?? 0);
    $cases   = (int)($s['cases_count'] ?? 0);
    $updates = (int)($s['updated_count'] ?? 0);

    $score = ($total * 1) + ($tasks * 2) + ($cases * 3) + ($updates * 1);

    if ($score >= 20) return ['نشط جدًا', '🔥', '#22c55e'];
    if ($score >= 10)  return ['نشط', '👍', '#16a34a'];
    if ($score >= 5)  return ['متوسط', '⚖️', '#eab308'];
    if ($score >= 3)  return ['كسول', '😴', '#f97316'];

    return ['مهمل', '⚠️', '#ef4444'];
}

render_layout_start('سجل النشاطات');
?>

<style>
.logs-box{
  padding:20px;
}

.logs-search{
  margin-bottom:18px;
  background:linear-gradient(145deg,rgba(255,255,255,.08),rgba(255,255,255,.04));
  border:1px solid rgba(255,255,255,.10);
  border-radius:18px;
  padding:14px;
  display:flex;
  gap:10px;
  align-items:center;
}

.logs-search input{
  flex:1;
  height:46px;
  border-radius:14px;
  border:1px solid rgba(255,255,255,.12);
  background:rgba(255,255,255,.08);
  color:#fff;
  padding:0 14px;
  outline:none;
  font-size:14px;
}

.logs-search input::placeholder{
  color:rgba(255,255,255,.55);
}

.logs-search button,
.logs-search a{
  height:46px;
  border-radius:14px;
  border:none;
  padding:0 18px;
  color:#fff;
  text-decoration:none;
  font-weight:900;
  cursor:pointer;
  display:flex;
  align-items:center;
  justify-content:center;
}

.logs-search button{
  background:#006a7a;
}

.logs-search a{
  background:rgba(255,255,255,.10);
}

.stats-grid{
  display:grid;
  grid-template-columns:repeat(4,minmax(0,1fr));
  gap:14px;
  margin-bottom:18px;
}

.employee-stat-card{
  background:linear-gradient(145deg,rgba(255,255,255,.08),rgba(255,255,255,.04));
  border:1px solid rgba(255,255,255,.09);
  border-radius:18px;
  padding:16px;
  color:#fff;
}

.employee-stat-name{
  font-size:15px;
  font-weight:900;
  margin-bottom:10px;
}

.employee-stat-total{
  font-size:32px;
  font-weight:900;
  color:#FFD76A;
  line-height:1;
}

.employee-stat-label{
  margin-top:6px;
  font-size:12px;
  color:rgba(255,255,255,.65);
}

.employee-stat-mini{
  margin-top:14px;
  display:grid;
  grid-template-columns:1fr 1fr;
  gap:8px;
}

.employee-stat-mini span{
  background:rgba(255,255,255,.06);
  border:1px solid rgba(255,255,255,.08);
  border-radius:10px;
  padding:7px 8px;
  font-size:12px;
  color:rgba(255,255,255,.82);
}

.employee-status-badge{
  display:inline-flex;
  align-items:center;
  gap:5px;
  margin-top:10px;
  padding:7px 10px;
  border-radius:999px;
  color:#fff;
  font-size:12px;
  font-weight:900;
}

.log-item{
  background:rgba(255,255,255,.05);
  border:1px solid rgba(255,255,255,.08);
  border-radius:14px;
  padding:14px;
  margin-bottom:10px;
  display:flex;
  align-items:center;
  gap:12px;
}

.log-icon{
  width:42px;
  height:42px;
  border-radius:12px;
  display:flex;
  align-items:center;
  justify-content:center;
  font-size:18px;
  flex:0 0 42px;
}

.log-content{
  flex:1;
  min-width:0;
}

.log-title{
  font-weight:800;
  color:#fff;
}

.log-desc{
  font-size:13px;
  color:#ccc;
  margin-top:4px;
}

.log-meta{
  margin-top:8px;
  font-size:12px;
  color:rgba(255,255,255,.68);
  display:flex;
  flex-wrap:wrap;
  gap:6px 10px;
  align-items:center;
}

.log-meta span{
  display:inline-flex;
  align-items:center;
  gap:4px;
}

.log-actions{
  display:flex;
  gap:8px;
  align-items:center;
  flex:0 0 auto;
}

.log-open{
  min-width:58px;
  height:36px;
  border-radius:12px;
  background:rgba(255,255,255,.07);
  border:1px solid rgba(255,255,255,.10);
  color:#fff;
  display:flex;
  align-items:center;
  justify-content:center;
  font-size:13px;
  font-weight:800;
  text-decoration:none;
}

.log-delete-btn{
  width:36px;
  height:36px;
  border-radius:10px;
  border:none;
  background:#dc2626;
  color:#fff;
  cursor:pointer;
  font-size:14px;
  display:flex;
  align-items:center;
  justify-content:center;
  transition:.2s;
}

.log-delete-btn:hover{
  background:#b91c1c;
  transform:scale(1.05);
}

.logs-empty{
  padding:20px;
  border-radius:14px;
  background:rgba(255,255,255,.05);
  color:rgba(255,255,255,.7);
  text-align:center;
}

.search-result-note{
  margin-bottom:14px;
  color:rgba(255,255,255,.72);
  font-size:13px;
}

@media(max-width:1100px){
  .stats-grid{
    grid-template-columns:repeat(2,minmax(0,1fr));
  }
}

@media(max-width:700px){
  .log-item{
    align-items:flex-start;
    flex-wrap:wrap;
  }

  .log-actions{
    width:100%;
    justify-content:flex-start;
  }
}

@media(max-width:650px){
  .stats-grid{
    grid-template-columns:1fr;
  }

  .logs-search{
    flex-direction:column;
  }

  .logs-search input,
  .logs-search button,
  .logs-search a{
    width:100%;
  }
}
.logs-box{
  width:100% !important;
  max-width:none !important;
  margin:0 !important;
  padding:24px !important;
  box-sizing:border-box;
}

.layout-content,
.main-content,
.page-content,
.dashboard-content,
.content,
.wrapper{
  width:100% !important;
  max-width:none !important;
}

.stats-grid{
  width:100%;
  grid-template-columns:repeat(auto-fit,minmax(260px,1fr)) !important;
}

.log-item{
  width:100%;
  box-sizing:border-box;
}

.logs-search{
  width:100%;
  box-sizing:border-box;
}
</style>

<div class="logs-box">

  <form class="logs-search" method="get" action="activity_logs.php">
    <input 
      type="text"
      name="q"
      value="<?= h($q) ?>"
      placeholder="بحث ذكي: اسم الموظف، القسم، نوع النشاط، الوصف، التاريخ..."
    >

    <button type="submit">بحث</button>

    <?php if ($q !== ''): ?>
      <a href="activity_logs.php">مسح</a>
    <?php endif; ?>
  </form>

  <?php if ($q !== ''): ?>
    <div class="search-result-note">
      نتائج البحث عن: <?= h($q) ?> — عدد النتائج: <?= count($logs) ?>
    </div>
  <?php endif; ?>

  <div class="stats-grid">
    <?php foreach ($employeeStats as $s): ?>
      <?php [$statusText, $statusIcon, $statusColor] = get_employee_status($s); ?>

      <div class="employee-stat-card">
        <div class="employee-stat-name">
          <?= h($s['employee_name']) ?>
        </div>

        <div class="employee-stat-total">
          <?= (int)$s['total_actions'] ?>
        </div>

        <div class="employee-stat-label">إجمالي الإنجازات</div>

        <div class="employee-status-badge" style="background:<?= h($statusColor) ?>">
          <?= h($statusIcon) ?> <?= h($statusText) ?>
        </div>

        <div class="employee-stat-mini">
          <span>إضافة: <?= (int)$s['created_count'] ?></span>
          <span>تعديل: <?= (int)$s['updated_count'] ?></span>
          <span>حذف: <?= (int)$s['deleted_count'] ?></span>
          <span>عملاء: <?= (int)$s['clients_count'] ?></span>
          <span>مهام: <?= (int)$s['tasks_count'] ?></span>
          <span>قضايا: <?= (int)$s['cases_count'] ?></span>
        </div>
      </div>
    <?php endforeach; ?>
  </div>

  <?php if (empty($logs)): ?>

    <div class="logs-empty">لا توجد سجلات حالياً.</div>

  <?php else: ?>

    <?php foreach ($logs as $log): ?>
      <?php
        try {
            $createdAt = !empty($log['created_at'])
                ? new DateTime((string)$log['created_at'], new DateTimeZone('Asia/Dubai'))
                : new DateTime('now', new DateTimeZone('Asia/Dubai'));
        } catch (Throwable $e) {
            $createdAt = new DateTime('now', new DateTimeZone('Asia/Dubai'));
        }

        $dateText = $createdAt->format('Y-m-d');
        $timeText = str_replace(['AM', 'PM'], ['صباحاً', 'مساءً'], $createdAt->format('h:i A'));

        $color = !empty($log['color']) ? (string)$log['color'] : '#0ea5e9';
        $icon  = !empty($log['icon']) ? (string)$log['icon'] : '📝';
      ?>

      <div class="log-item">

        <div class="log-icon" style="background:<?= h($color) ?>">
          <?= h($icon) ?>
        </div>

        <div class="log-content">
          <div class="log-title">
            <?= h($log['title'] ?? 'نشاط جديد') ?>
          </div>

          <div class="log-desc">
            <?= h($log['description'] ?? '') ?>
          </div>

          <div class="log-meta">
            <span>الموظف: <?= h($log['employee_name'] ?? 'غير معروف') ?></span>
            <span>القسم: <?= h($log['module'] ?? '-') ?></span>
            <span>النوع: <?= h($log['action_type'] ?? '-') ?></span>
            <span>التاريخ: <?= h($dateText) ?></span>
            <span>الساعة: <?= h($timeText) ?></span>
          </div>
        </div>

        <div class="log-actions">
          <?php if (!empty($log['url'])): ?>
            <a class="log-open" href="<?= h($log['url']) ?>">فتح</a>
          <?php endif; ?>

          <?php if ($canDeleteLogs): ?>
            <form method="post" style="margin:0;">
              <input type="hidden" name="delete_log_id" value="<?= (int)$log['id'] ?>">
              <input type="hidden" name="current_q" value="<?= h($q) ?>">

              <button 
                type="submit" 
                class="log-delete-btn" 
                onclick="return confirm('هل تريد حذف هذا السجل؟')"
              >
                🗑
              </button>
            </form>
          <?php endif; ?>
        </div>

      </div>
    <?php endforeach; ?>

  <?php endif; ?>

</div>

<?php render_layout_end(); ?>