<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/portal_auth.php';
auth_require_employee_portal();

$pdo = crm_pdo();
$page_title = 'Time Clock';

$isAdminView = auth_is_admin_like();
$employeeId = auth_employee_id();
if (!$isAdminView && $employeeId <= 0) {
    http_response_code(403);
    exit('Employee record not linked.');
}

$ok = '';
$errors = [];

function gp_find_open_shift(PDO $pdo, int $employeeId): ?array
{
    $stmt = $pdo->prepare("SELECT * FROM work_sessions WHERE employee_id = :eid AND end_time IS NULL ORDER BY id DESC LIMIT 1");
    $stmt->execute([':eid' => $employeeId]);
    $row = $stmt->fetch();
    return $row ?: null;
}

if (!$isAdminView && $_SERVER['REQUEST_METHOD'] === 'POST') {
    gp_require_csrf();
    $action = trim((string)($_POST['action'] ?? ''));
    $projectId = (int)($_POST['project_id'] ?? 0);

    if ($action === 'start') {
        if ($projectId <= 0) {
            $errors[] = 'Project is required.';
        } else {
            $open = gp_find_open_shift($pdo, $employeeId);
            if ($open) {
                $errors[] = 'There is already an open shift.';
            } else {
                $p = $pdo->prepare("SELECT work_region_type, title FROM projects WHERE id = :id LIMIT 1");
                $p->execute([':id' => $projectId]);
                $project = $p->fetch();

                if (!$project) {
                    $errors[] = 'Project not found.';
                } else {
                    $type = (string)($project['work_region_type'] ?? 'local');
                    if (!in_array($type, ['local', 'outstation'], true)) {
                        $type = 'local';
                    }

                    $rateQ = $pdo->prepare("SELECT hourly_rate_local, hourly_rate_outstation FROM employees WHERE id = :id LIMIT 1");
                    $rateQ->execute([':id' => $employeeId]);
                    $emp = $rateQ->fetch();

                    if (!$emp) {
                        $errors[] = 'Employee record not found.';
                    } else {
                        $rate = $type === 'outstation'
                            ? (float)($emp['hourly_rate_outstation'] ?? 0)
                            : (float)($emp['hourly_rate_local'] ?? 0);

                        if ($rate <= 0) {
                            $errors[] = 'Hourly rate is not set for this employee. Set hourly_rate_local / hourly_rate_outstation first.';
                        } else {
                            $stmt = $pdo->prepare("
                                INSERT INTO work_sessions
                                    (employee_id, project_id, work_date, start_time, hourly_rate, work_type)
                                VALUES
                                    (:employee_id, :project_id, :work_date, :start_time, :hourly_rate, :work_type)
                            ");
                            $stmt->execute([
                                ':employee_id' => $employeeId,
                                ':project_id' => $projectId,
                                ':work_date' => date('Y-m-d'),
                                ':start_time' => date('Y-m-d H:i:s'),
                                ':hourly_rate' => $rate,
                                ':work_type' => $type,
                            ]);
                            $ok = 'Shift started.';
                        }
                    }
                }
            }
        }
    }

    if ($action === 'stop') {
        $stmt = $pdo->prepare("UPDATE work_sessions SET end_time = NOW() WHERE employee_id = :eid AND end_time IS NULL");
        $stmt->execute([':eid' => $employeeId]);
        $ok = 'Shift stopped.';
    }
}

if ($isAdminView) {
    // Admin sees all recent sessions across all employees
    $projects = [];
    $current = null;
    $hist = $pdo->prepare("
        SELECT ws.*, p.code, p.title, e.full_name AS employee_name
        FROM work_sessions ws
        LEFT JOIN projects p ON p.id = ws.project_id
        LEFT JOIN employees e ON e.id = ws.employee_id
        ORDER BY ws.id DESC
        LIMIT 100
    ");
    $hist->execute();
    $rows = $hist->fetchAll();
} else {
    $projects = $pdo->prepare("
        SELECT DISTINCT p.id, p.code, p.title, p.work_region_type
        FROM project_assignments pa
        JOIN projects p ON p.id = pa.project_id
        WHERE pa.employee_id = :eid
        ORDER BY p.id DESC
    ");
    $projects->execute([':eid' => $employeeId]);
    $projects = $projects->fetchAll();

    $current = gp_find_open_shift($pdo, $employeeId);
    if ($current && !empty($current['project_id'])) {
        $st = $pdo->prepare("SELECT code, title FROM projects WHERE id = :id LIMIT 1");
        $st->execute([':id' => (int)$current['project_id']]);
        $project = $st->fetch();
        if ($project) {
            $current['code'] = $project['code'];
            $current['title'] = $project['title'];
        }
    }

    $hist = $pdo->prepare("
        SELECT ws.*, p.code, p.title
        FROM work_sessions ws
        LEFT JOIN projects p ON p.id = ws.project_id
        WHERE ws.employee_id = :eid
        ORDER BY ws.id DESC
        LIMIT 50
    ");
    $hist->execute([':eid' => $employeeId]);
    $rows = $hist->fetchAll();
}

include __DIR__ . '/../includes/header.php';
?>
<style>
.timeclock-hero{display:grid;grid-template-columns:1fr 1fr;gap:14px}
.timeclock-live-box{border:1px solid rgba(15,23,42,.08);border-radius:18px;padding:16px;background:rgba(255,255,255,.35)}
.timeclock-live-title{font-size:.85rem;opacity:.72;margin-bottom:6px}
.timeclock-elapsed{font-size:2rem;font-weight:800;letter-spacing:.03em;line-height:1.1}
.timeclock-meta-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:12px}
.timeclock-meta-item{border:1px solid rgba(15,23,42,.06);border-radius:14px;padding:10px 12px;background:rgba(255,255,255,.25)}
.timeclock-meta-label{font-size:.8rem;opacity:.68;margin-bottom:4px}
.timeclock-meta-value{font-weight:700}
@media (max-width:900px){.timeclock-hero{grid-template-columns:1fr}.timeclock-elapsed{font-size:1.6rem}}
</style>

<div class="page-header">
  <div class="page-header-title">
    <h1>Time Clock</h1>
    <span>Simple start / stop tracking</span>
  </div>
</div>

<div class="grid-2">
<?php if ($isAdminView): ?>
  <!-- Admin overview mode -->
  <div class="card" style="grid-column:1/-1">
    <div class="page-header-title"><h1 style="font-size:1.05rem">All Employee Sessions</h1><span>Admin overview · Last 100 records</span></div>
    <?php if (!$rows): ?><p class="small">No work sessions recorded yet.</p><?php else: ?>
      <div class="table-responsive">
        <table class="table">
          <thead><tr><th>Date</th><th>Employee</th><th>Project</th><th>Start</th><th>End</th><th>Type</th><th>Rate</th></tr></thead>
          <tbody>
            <?php foreach ($rows as $r): ?>
              <tr>
                <td><?php echo h((string)$r['work_date']); ?></td>
                <td><?php echo h(($r['employee_name'] ?? '') ?: 'N/A'); ?></td>
                <td><?php echo h(($r['code'] ?? '') . ' · ' . ($r['title'] ?? '')); ?></td>
                <td><?php echo h((string)$r['start_time']); ?></td>
                <td><?php echo h((string)($r['end_time'] ?? '')); ?></td>
                <td><?php echo h((string)$r['work_type']); ?></td>
                <td>€ <?php echo h(number_format((float)($r['hourly_rate'] ?? 0), 2)); ?></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>
<?php else: ?>
  <!-- Employee self-service mode -->
  <div class="card">
    <?php if ($ok): ?><div class="alert-success"><?php echo h($ok); ?></div><?php endif; ?>
    <?php if ($errors): ?><div class="alert-danger"><?php echo h(implode(' ', $errors)); ?></div><?php endif; ?>

    <div class="page-header-title">
      <h1 style="font-size:1.05rem">Current shift</h1>
      <span><?php echo $current ? 'open' : 'No open shift'; ?></span>
    </div>

    <?php if ($current): ?>
      <div class="timeclock-hero">
        <div class="timeclock-live-box">
          <div class="timeclock-live-title">Elapsed time</div>
          <div class="timeclock-elapsed" id="elapsed-timer" data-start-time="<?php echo h((string)$current['start_time']); ?>">00:00:00</div>
        </div>
        <div class="timeclock-live-box">
          <div class="timeclock-meta-grid">
            <div class="timeclock-meta-item"><div class="timeclock-meta-label">Project</div><div class="timeclock-meta-value"><?php echo h(($current['code'] ?? '') . ' · ' . ($current['title'] ?? '')); ?></div></div>
            <div class="timeclock-meta-item"><div class="timeclock-meta-label">Started</div><div class="timeclock-meta-value"><?php echo h((string)$current['start_time']); ?></div></div>
            <div class="timeclock-meta-item"><div class="timeclock-meta-label">Work type</div><div class="timeclock-meta-value"><?php echo h((string)$current['work_type']); ?></div></div>
            <div class="timeclock-meta-item"><div class="timeclock-meta-label">Hourly rate snapshot</div><div class="timeclock-meta-value">€ <?php echo h(number_format((float)($current['hourly_rate'] ?? 0), 2)); ?></div></div>
          </div>
        </div>
      </div>
      <div class="form-actions" style="margin-top:14px">
        <form method="post" style="display:inline">
      <?php echo csrf_field(); ?>
          <input type="hidden" name="action" value="stop">
          <button class="btn btn-primary" type="submit">Stop</button>
        </form>
      </div>
    <?php else: ?>
      <form method="post">
      <?php echo csrf_field(); ?>
        <input type="hidden" name="action" value="start">
        <div class="form-grid">
          <div class="form-group">
            <label>Project</label>
            <select name="project_id" required>
              <option value="0">Select project...</option>
              <?php foreach ($projects as $p): ?>
                <option value="<?php echo (int)$p['id']; ?>"><?php echo h(($p['code'] ?? '') . ' · ' . ($p['title'] ?? '') . ' · ' . ($p['work_region_type'] ?? 'local')); ?></option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>
        <div class="form-actions"><button class="btn btn-primary" type="submit">Start</button></div>
      </form>
    <?php endif; ?>
  </div>

  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem">Recent sessions</h1><span>Last 50 records</span></div>
    <?php if (!$rows): ?><p class="small">No work sessions yet.</p><?php else: ?>
      <div class="table-responsive">
        <table class="table">
          <thead><tr><th>Date</th><th>Project</th><th>Start</th><th>End</th><th>Type</th><th>Rate</th></tr></thead>
          <tbody>
            <?php foreach ($rows as $r): ?>
              <tr>
                <td><?php echo h((string)$r['work_date']); ?></td>
                <td><?php echo h(($r['code'] ?? '') . ' · ' . ($r['title'] ?? '')); ?></td>
                <td><?php echo h((string)$r['start_time']); ?></td>
                <td><?php echo h((string)($r['end_time'] ?? '')); ?></td>
                <td><?php echo h((string)$r['work_type']); ?></td>
                <td>€ <?php echo h(number_format((float)($r['hourly_rate'] ?? 0), 2)); ?></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>
<?php endif; ?>
</div>

<script>
(function () {
  const timerEl = document.getElementById('elapsed-timer');
  if (!timerEl) return;
  const raw = timerEl.getAttribute('data-start-time');
  if (!raw) return;

  function parseLocalDateTime(str) {
    const normalized = str.replace(' ', 'T');
    const d = new Date(normalized);
    if (!isNaN(d.getTime())) return d;
    const m = str.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2}):(\d{2})$/);
    if (!m) return null;
    return new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6]));
  }

  const start = parseLocalDateTime(raw);
  if (!start) return;

  function pad(n) { return String(n).padStart(2, '0'); }
  function render() {
    const now = new Date();
    let diff = Math.floor((now.getTime() - start.getTime()) / 1000);
    if (diff < 0) diff = 0;
    const hours = Math.floor(diff / 3600);
    const minutes = Math.floor((diff % 3600) / 60);
    const seconds = diff % 60;
    timerEl.textContent = pad(hours) + ':' + pad(minutes) + ':' + pad(seconds);
  }
  render();
  setInterval(render, 1000);
})();
</script>

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