<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
auth_require_login();

$role = strtolower(trim((string)((auth_user()['role'] ?? ''))));

if (!gp_is_full_project_access_role($role) && !gp_is_secretary_like_role($role)) {
    redirect(auth_current_redirect_path());
}

$pdo = crm_pdo();
$page_title = 'Dashboard';

if (!function_exists('gp_setting')) {
    function gp_setting(PDO $pdo, string $key, string $default): string {
        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = :k LIMIT 1");
        $stmt->execute([':k' => $key]);
        $v = $stmt->fetchColumn();
        return $v !== false ? (string)$v : $default;
    }
}

$customers = (int)$pdo->query("SELECT COUNT(*) FROM customers WHERE active = 1")->fetchColumn();
$projects = (int)$pdo->query("SELECT COUNT(*) FROM projects")->fetchColumn();
$activeProjects = (int)$pdo->query("SELECT COUNT(*) FROM projects WHERE status IN ('active','planned','in_progress')")->fetchColumn();
$employees = (int)$pdo->query("SELECT COUNT(*) FROM employees WHERE active = 1")->fetchColumn();
$vehicles = (int)$pdo->query("SELECT COUNT(*) FROM vehicles WHERE active = 1")->fetchColumn();
$calendarView = gp_setting($pdo, 'calendar_default_view', 'dayGridMonth');

// Permission checks
$canViewFinancials = function_exists('gp_user_perm') ? gp_user_perm($pdo, 'perm_financials') : gp_is_admin_like();
$canViewCostings   = function_exists('gp_user_perm') ? gp_user_perm($pdo, 'perm_costings')   : gp_is_admin_like();

// Recent activity
$recentLogs = [];
try {
    $stmt = $pdo->query("
        SELECT sl.*, u.username 
        FROM system_logs sl 
        LEFT JOIN users u ON u.id = sl.user_id 
        ORDER BY sl.created_at DESC 
        LIMIT 8
    ");
    $recentLogs = $stmt->fetchAll();
} catch (Throwable $e) {}

// Pending alerts (vehicles expiring soon)
$vehicleAlerts = [];
try {
    $threshold = date('Y-m-d', strtotime('+30 days'));
    $stmt = $pdo->prepare("
        SELECT license_plate, 
               insurance_expiry, kteo_expiry, next_service_date
        FROM vehicles 
        WHERE active = 1 
        AND (
            (insurance_expiry IS NOT NULL AND insurance_expiry != '0000-00-00' AND insurance_expiry <= ?)
            OR (kteo_expiry IS NOT NULL AND kteo_expiry != '0000-00-00' AND kteo_expiry <= ?)
            OR (next_service_date IS NOT NULL AND next_service_date != '0000-00-00' AND next_service_date <= ?)
        )
        ORDER BY LEAST(
            IF(insurance_expiry IS NULL OR insurance_expiry = '0000-00-00', '9999-12-31', insurance_expiry),
            IF(kteo_expiry IS NULL OR kteo_expiry = '0000-00-00', '9999-12-31', kteo_expiry),
            IF(next_service_date IS NULL OR next_service_date = '0000-00-00', '9999-12-31', next_service_date)
        ) ASC
        LIMIT 5
    ");
    $stmt->execute([$threshold, $threshold, $threshold]);
    $vehicleAlerts = $stmt->fetchAll();
} catch (Throwable $e) {}

// Unscheduled Projects
$unscheduledProjects = [];
try {
    $stmt = $pdo->query("
        SELECT p.id, p.title, p.code, c.name as customer_name, p.status 
        FROM projects p
        LEFT JOIN customers c ON p.customer_id = c.id
        WHERE p.status NOT IN ('completed', 'cancelled') 
        AND (p.start_date IS NULL OR p.start_date = '0000-00-00' OR p.start_date = '' OR p.start_date LIKE '0000%')
        ORDER BY p.created_at DESC
    ");
    $unscheduledProjects = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    file_put_contents(__DIR__.'/debug.txt', $e->getMessage());
}

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1>Dashboard</h1>
    <span>Overview + project calendar</span>
  </div>
  <div class="page-header-actions">
    <a class="btn btn-secondary btn-sm" href="/gopools/public/settings/email_to_project.php">Email to project settings</a>
  </div>
</div>

<?php include __DIR__ . '/../includes/assistant.php'; ?>

<div class="grid-4" style="margin-bottom:24px">
  <div class="card stat-card">
    <div class="stat-info">
      <div class="small">Active Customers</div>
      <div class="stat-value"><?php echo $customers; ?></div>
    </div>
    <div class="stat-icon" style="background:rgba(37,99,235,0.15); color:var(--primary);">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
    </div>
  </div>
  
  <div class="card stat-card">
    <div class="stat-info">
      <div class="small">Projects</div>
      <div class="stat-value"><?php echo $projects; ?></div>
    </div>
    <div class="stat-icon" style="background:rgba(16,185,129,0.15); color:var(--success);">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/><path d="M8 14h.01"/><path d="M12 14h.01"/><path d="M16 14h.01"/><path d="M8 18h.01"/><path d="M12 18h.01"/><path d="M16 18h.01"/></svg>
    </div>
  </div>

  <div class="card stat-card">
    <div class="stat-info">
      <div class="small">Active Employees</div>
      <div class="stat-value"><?php echo $employees; ?></div>
    </div>
    <div class="stat-icon" style="background:rgba(245,158,11,0.15); color:#f59e0b;">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
    </div>
  </div>

  <div class="card stat-card">
    <div class="stat-info">
      <div class="small">Active Vehicles</div>
      <div class="stat-value"><?php echo $vehicles; ?></div>
    </div>
    <div class="stat-icon" style="background:rgba(139,92,246,0.15); color:#8b5cf6;">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="1" y="3" width="15" height="13"/><polygon points="16 8 20 8 23 11 23 16 16 16 16 8"/><circle cx="5.5" cy="18.5" r="2.5"/><circle cx="18.5" cy="18.5" r="2.5"/></svg>
    </div>
  </div>
</div>

<style>
/* ─── Modern Calendar Overrides (Minimalist Soft) ─── */
#project-calendar {
  --fc-border-color: rgba(15, 23, 42, 0.05);
  --fc-button-bg-color: #f8fafc;
  --fc-button-border-color: rgba(15, 23, 42, 0.08);
  --fc-button-text-color: #475569;
  --fc-button-hover-bg-color: #f1f5f9;
  --fc-button-hover-border-color: rgba(15, 23, 42, 0.12);
  --fc-button-active-bg-color: #e2e8f0;
  --fc-today-bg-color: rgba(37, 99, 235, 0.03);
  font-family: var(--font-sans);
}

#project-calendar .fc-toolbar-title {
  font-size: 1.25rem; font-weight: 700; color: var(--gp-text);
}

#project-calendar .fc-col-header-cell {
  padding: 12px 0; background: transparent; border: none;
}
#project-calendar .fc-col-header-cell-cushion {
  font-size: 0.72rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.08em; color: var(--gp-muted); text-decoration: none;
}

#project-calendar .fc-daygrid-day-number {
  font-size: 0.8rem; font-weight: 600; color: var(--gp-muted); padding: 8px 12px; text-decoration: none;
}

#project-calendar .fc-scrollgrid {
  border-radius: 16px; overflow: hidden; border: 1px solid rgba(15, 23, 42, 0.05);
}

/* Event Styling (The Modern Card/Pill Shape) */
#project-calendar .fc-event {
  border: none !important;
  border-radius: 12px !important; /* Slightly more card-like than full capsule */
  padding: 6px 12px !important; /* MUCH more padding */
  margin: 4px 6px !important; /* Better spacing between multiple events */
  box-shadow: 0 4px 10px rgba(0,0,0,0.08); /* Deeper shadow for depth */
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: visible !important;
}
#project-calendar .fc-event:hover {
  transform: translateY(-2px) scale(1.02);
  box-shadow: 0 8px 24px rgba(0,0,0,0.12);
  z-index: 100;
}

#project-calendar .fc-event-main {
  padding: 0 !important;
}

.fc-event-title {
  font-weight: 700 !important;
  font-size: 0.9rem !important;
  color: white;
  letter-spacing: -0.01em; /* Sharper spacing */
}

/* Responsive adjustments */
@media (max-width: 768px) {
  #project-calendar .fc-toolbar { flex-direction: column; gap: 12px; }
}

[data-theme='dark'] #project-calendar {
  --fc-border-color: rgba(255, 255, 255, 0.06);
  --fc-button-bg-color: rgba(255, 255, 255, 0.03);
  --fc-button-text-color: #a8b5cd;
}
</style>

<div class="card" style="margin-bottom:24px; padding:24px;">
  <div class="page-header-title" style="margin-bottom:24px;">
    <h1 style="font-size:1.4rem">Project Calendar</h1>
    <span style="color:var(--gp-muted); font-size:0.9rem;">Modern minimalist view. Drag projects to reschedule.</span>
  </div>
  <div id="project-calendar"></div>
</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.17/index.global.min.css">
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.17/index.global.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
  var calendarEl = document.getElementById('project-calendar');
  if (!calendarEl) return;

  var calendar = new FullCalendar.Calendar(calendarEl, {
    initialView: '<?php echo h($calendarView); ?>',
    firstDay: 1,
    height: 'auto',
    editable: true,
    events: '/gopools/public/api/calendar_events.php',
    eventContent: function(arg) {
      let weatherHtml = '';
      if (arg.event.extendedProps.weather) {
        const w = arg.event.extendedProps.weather;
        // SIGNIFICANTLY larger weather badge
        // Sharper weather badge without blur
        weatherHtml = `<span style="display:inline-flex; align-items:center; gap:4px; background:rgba(255,255,255,0.4); padding:4px 10px; border-radius:10px; margin-left:10px; font-size:0.85em; font-weight:800; color:white; border: 1px solid rgba(255,255,255,0.2);">
          <img src="https://openweathermap.org/img/wn/${w.icon}.png" style="width:24px; height:24px;" alt="${w.description}">
          ${Math.round(w.temp)}°
        </span>`;
      }
      
      const isVisit = arg.event.extendedProps.type === 'visit';
      const indicator = isVisit ? '📍 ' : '';
      
      return {
        html: `<div class="fc-event-main-frame" style="display:flex; align-items:center; justify-content:space-between; width:100%; min-height:32px;">
          <div class="fc-event-title-container" style="flex:1; min-width:0;">
            <div class="fc-event-title" style="white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">
              ${indicator}${arg.event.title}
            </div>
          </div>
          ${weatherHtml}
        </div>`
      };
    },
    eventClick: function(info) {
      // For visits, use the parent project_id
      const id = info.event.extendedProps.project_id || info.event.id;
      window.location.href = '/gopools/public/projects/edit.php?id=' + id;
    },
    eventDrop: function(info) {
      gpUpdateProjectDates(info);
    },
    eventResize: function(info) {
      gpUpdateProjectDates(info);
    }
  });

  function gpUpdateProjectDates(info) {
    var endStr = info.event.endStr || info.event.startStr;
    
    fetch('/gopools/public/api/calendar_update.php', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({
        id: info.event.id,
        start: info.event.startStr,
        end: endStr
      })
    }).then(function(r){ return r.json(); }).then(function(resp){
      if (!resp.ok) {
        info.revert();
        alert(resp.error || 'Could not update project dates.');
      }
    }).catch(function(){
      info.revert();
      alert('Could not update project dates.');
    });
  }

  calendar.render();
});
</script>

<div class="grid-2" style="margin-bottom:24px">
  <!-- Recent Activity -->
  <div class="card card-static">
    <div class="page-header-title" style="margin-bottom:16px;">
      <h1 style="font-size:1.1rem">Recent Activity</h1>
      <span>Latest system events</span>
    </div>
    <?php if (!$recentLogs): ?>
      <p class="small">No activity recorded yet.</p>
    <?php else: ?>
      <div style="display:flex; flex-direction:column; gap:2px;">
        <?php foreach ($recentLogs as $log):
          $actionColors = [
            'LOGIN_SUCCESS' => '#10b981',
            'LOGOUT' => '#64748b',
            'LOGIN_FAILED' => '#ef4444',
            'PROJECT_CREATE' => '#3b82f6',
            'PROJECT_UPDATE' => '#8b5cf6',
          ];
          $color = $actionColors[$log['action_type']] ?? '#64748b';
        ?>
          <div style="display:flex; align-items:center; gap:12px; padding:10px 0; border-bottom:1px solid var(--border);">
            <div style="width:8px; height:8px; border-radius:50%; background:<?php echo $color; ?>; flex-shrink:0;"></div>
            <div style="flex:1; min-width:0;">
              <div style="font-size:0.85rem; font-weight:600; color:var(--text);"><?php echo h($log['action_type']); ?></div>
              <div style="font-size:0.78rem; color:var(--muted); white-space:nowrap; overflow:hidden; text-overflow:ellipsis;"><?php echo h($log['details'] ?: ($log['entity_type'] ? $log['entity_type'] . ' #' . $log['entity_id'] : '')); ?></div>
            </div>
            <div style="flex-shrink:0; text-align:right;">
              <div style="font-size:0.75rem; font-weight:600; color:var(--muted);"><?php echo h($log['username'] ?: 'System'); ?></div>
              <div style="font-size:0.7rem; color:var(--muted);"><?php echo h(gp_date($log['created_at'], true)); ?></div>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
      <div style="margin-top:12px; text-align:right;">
        <a class="btn btn-sm btn-secondary" href="/gopools/public/settings/logs.php" style="font-size:0.8rem;">View all logs →</a>
      </div>
    <?php endif; ?>
  </div>

  <!-- Vehicle Alerts -->
  <div class="card card-static">
    <div class="page-header-title" style="margin-bottom:16px;">
      <h1 style="font-size:1.1rem">⚠️ Upcoming Deadlines</h1>
      <span>Vehicles expiring within 30 days</span>
    </div>
    <?php if (!$vehicleAlerts): ?>
      <div class="empty-state" style="padding:24px;">
        <div class="empty-state-icon" style="font-size:1.5rem;">✅</div>
        <div class="empty-state-title" style="font-size:0.95rem;">All clear</div>
        <div class="empty-state-desc">No upcoming vehicle expirations</div>
      </div>
    <?php else: ?>
      <?php $today = date('Y-m-d'); foreach ($vehicleAlerts as $va): ?>
        <div style="padding:12px; margin-bottom:8px; border-radius:12px; border:1px solid var(--border); background:rgba(245,158,11,0.04);">
          <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:6px;">
            <strong style="font-size:0.95rem;"><?php echo h($va['license_plate']); ?></strong>
            <a class="btn btn-sm btn-secondary" href="/gopools/public/vehicles/edit.php?id=<?php echo ''; ?>" style="font-size:0.75rem; padding:4px 10px;">View</a>
          </div>
          <div style="display:flex; gap:8px; flex-wrap:wrap;">
            <?php if ($va['insurance_expiry'] && $va['insurance_expiry'] !== '0000-00-00' && $va['insurance_expiry'] <= date('Y-m-d', strtotime('+30 days'))): ?>
              <span class="badge <?php echo $va['insurance_expiry'] < $today ? 'badge-danger' : 'badge-warning'; ?>">Insurance: <?php echo h(gp_date($va['insurance_expiry'])); ?></span>
            <?php endif; ?>
            <?php if ($va['kteo_expiry'] && $va['kteo_expiry'] !== '0000-00-00' && $va['kteo_expiry'] <= date('Y-m-d', strtotime('+30 days'))): ?>
              <span class="badge <?php echo $va['kteo_expiry'] < $today ? 'badge-danger' : 'badge-warning'; ?>">KTEO: <?php echo h(gp_date($va['kteo_expiry'])); ?></span>
            <?php endif; ?>
            <?php if ($va['next_service_date'] && $va['next_service_date'] !== '0000-00-00' && $va['next_service_date'] <= date('Y-m-d', strtotime('+30 days'))): ?>
              <span class="badge <?php echo $va['next_service_date'] < $today ? 'badge-danger' : 'badge-warning'; ?>">Service: <?php echo h(gp_date($va['next_service_date'])); ?></span>
            <?php endif; ?>
          </div>
        </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>
</div>

<!-- Floating Unscheduled Projects Panel -->
<div class="unscheduled-floating-panel" id="unscheduled-panel">
  <div class="unscheduled-header" onclick="toggleUnscheduled()" style="cursor:pointer;">
    <div style="display:flex; align-items:center; gap:8px;">
      <h3>📋 <?php echo gp_tr($pdo, 'unscheduled_projects'); ?></h3>
      <span class="badge"><?php echo count($unscheduledProjects); ?></span>
    </div>
    <span id="unscheduled-toggle-icon" style="color:var(--muted); font-size:1.2rem; transition:transform 0.3s;">−</span>
  </div>
  <div class="unscheduled-list" id="unscheduled-list-content">
    <?php if (empty($unscheduledProjects)): ?>
      <div class="unscheduled-empty">
        <?php echo gp_tr($pdo, 'no_unscheduled'); ?>
      </div>
    <?php else: ?>
      <?php foreach ($unscheduledProjects as $up): ?>
        <a href="/gopools/public/projects/edit.php?id=<?php echo $up['id']; ?>" class="unscheduled-card">
          <div class="unscheduled-title"><?php echo h($up['title']); ?></div>
          <div class="unscheduled-meta">
            <?php if($up['customer_name']) echo h($up['customer_name']) . ' • '; ?>
            <span style="color:var(--primary)"><?php echo gp_project_status_label($pdo, $up['status']); ?></span>
          </div>
        </a>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>
</div>

<script>
function toggleUnscheduled() {
  const content = document.getElementById('unscheduled-list-content');
  const icon = document.getElementById('unscheduled-toggle-icon');
  
  if (content.style.display === 'none') {
    content.style.display = 'flex';
    icon.style.transform = 'rotate(0deg)';
  } else {
    content.style.display = 'none';
    icon.style.transform = 'rotate(180deg)';
    icon.innerHTML = '+';
  }
  
  if(content.style.display === 'flex') {
      icon.innerHTML = '−';
  }
}
</script>

<style>
.unscheduled-floating-panel {
  position: fixed;
  right: 24px;
  top: 90px;
  width: 320px;
  max-height: calc(100vh - 120px);
  background: var(--card);
  border-radius: 16px;
  box-shadow: 0 10px 40px rgba(0,0,0,0.1);
  border: 1px solid var(--border);
  display: flex;
  flex-direction: column;
  z-index: 900;
  backdrop-filter: blur(16px);
}
:root[data-theme='dark'] .unscheduled-floating-panel {
  background: rgba(30, 41, 59, 0.85);
  box-shadow: 0 10px 40px rgba(0,0,0,0.4);
}
.unscheduled-header {
  padding: 16px;
  border-bottom: 1px solid var(--border);
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: rgba(0,0,0,0.02);
  border-radius: 16px 16px 0 0;
}
:root[data-theme='dark'] .unscheduled-header {
  background: rgba(255,255,255,0.02);
}
.unscheduled-header h3 {
  margin: 0;
  font-size: 0.95rem;
  font-weight: 700;
  color: var(--text);
}
.unscheduled-list {
  padding: 12px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 8px;
  scrollbar-width: thin;
}
.unscheduled-list::-webkit-scrollbar {
  width: 6px;
}
.unscheduled-list::-webkit-scrollbar-thumb {
  background: var(--border);
  border-radius: 10px;
}
.unscheduled-empty {
  padding: 24px 12px;
  text-align: center;
  font-size: 0.85rem;
  color: var(--muted);
}
.unscheduled-card {
  display: block;
  padding: 12px;
  background: var(--bg);
  border: 1px solid var(--border);
  border-radius: 10px;
  text-decoration: none;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}
.unscheduled-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0,0,0,0.06);
  border-color: var(--primary);
}
.unscheduled-title {
  font-size: 0.85rem;
  font-weight: 700;
  color: var(--text);
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.unscheduled-meta {
  font-size: 0.75rem;
  color: var(--muted);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* On smaller screens, hide it or make it relative */
@media (max-width: 1300px) {
  .unscheduled-floating-panel {
    position: relative;
    right: auto;
    top: auto;
    width: 100%;
    margin-top: 24px;
    max-height: 400px;
  }
}
</style>

<?php include __DIR__ . '/../includes/footer.php'; ?>
