<?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';

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();
$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');

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="/public/settings/email_to_project.php">Email to project settings</a>
  </div>
</div>

<div class="grid-4" style="margin-bottom:14px">
  <div class="card"><div class="small">Active customers</div><div style="font-size:2rem;font-weight:700"><?php echo $customers; ?></div></div>
  <div class="card"><div class="small">Projects</div><div style="font-size:2rem;font-weight:700"><?php echo $projects; ?></div></div>
  <div class="card"><div class="small">Active employees</div><div style="font-size:2rem;font-weight:700"><?php echo $employees; ?></div></div>
  <div class="card"><div class="small">Active vehicles</div><div style="font-size:2rem;font-weight:700"><?php echo $vehicles; ?></div></div>
</div>

<div class="card" style="margin-bottom:14px">
  <div class="page-header-title">
    <h1 style="font-size:1.1rem">Project calendar</h1>
    <span>Drag projects to move start and planned end dates</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); ?>',
    height: 'auto',
    editable: true,
    events: '/public/api/calendar_events.php',
    eventDrop: function(info) {
      fetch('/public/api/calendar_update.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
          id: info.event.id,
          start: info.event.startStr,
          end: info.event.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>
<?php include __DIR__ . '/../includes/footer.php'; ?>
