<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
auth_require_login();
$pdo = crm_pdo();

$user = auth_user();
$employeeId = (int)($user['employee_id'] ?? 0);
if ($employeeId <= 0) die('No employee linked to this user.');

$page_title = 'My work';

$uploadDirFs = __DIR__ . '/../uploads/work_photos';
$uploadDirWeb = '/gopools/public/uploads/work_photos';
if (!is_dir($uploadDirFs)) {
    @mkdir($uploadDirFs, 0775, true);
}

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]);
    $val = $stmt->fetchColumn();
    return $val !== false ? (string)$val : $default;
}

function gp_get_open_session(PDO $pdo, int $employeeId): ?array {
    $stmt = $pdo->prepare("
        SELECT ws.*, p.code AS project_code, p.title AS project_title
        FROM work_sessions ws
        LEFT JOIN projects p ON p.id = ws.project_id
        WHERE ws.employee_id = :eid
          AND ws.end_time IS NULL
        ORDER BY ws.start_time DESC
        LIMIT 1
    ");
    $stmt->execute([':eid' => $employeeId]);
    $row = $stmt->fetch();
    return $row ?: null;
}

$employeeStmt = $pdo->prepare("SELECT * FROM employees WHERE id = :id LIMIT 1");
$employeeStmt->execute([':id' => $employeeId]);
$employee = $employeeStmt->fetch();
if (!$employee) die('Employee not found.');

$projects = $pdo->query("
    SELECT id, code, title
    FROM projects
    ORDER BY code ASC, title ASC
")->fetchAll();

$errors = [];
$open = gp_get_open_session($pdo, $employeeId);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    gp_require_csrf();
    $action = $_POST['action'] ?? '';
    $open = gp_get_open_session($pdo, $employeeId);

    if ($action === 'start') {
        if ($open) {
            $errors[] = 'You already have an active session.';
        } else {
            $projectId = (int)($_POST['project_id'] ?? 0);
            if ($projectId <= 0) $projectId = null;
            $notes = trim($_POST['notes'] ?? '');

            $stmt = $pdo->prepare("
                INSERT INTO work_sessions
                    (employee_id, project_id, start_time, end_time, duration_minutes, notes, paused_at, pause_minutes_total)
                VALUES
                    (:eid, :pid, NOW(), NULL, NULL, :notes, NULL, 0)
            ");
            $stmt->execute([
                ':eid' => $employeeId,
                ':pid' => $projectId,
                ':notes' => $notes !== '' ? $notes : null,
            ]);
            redirect('/gopools/public/employees/my_work.php');
        }
    }

    if ($action === 'pause') {
        if (!$open) {
            $errors[] = 'No active session found.';
        } elseif (!empty($open['paused_at'])) {
            $errors[] = 'Session is already paused.';
        } else {
            $stmt = $pdo->prepare("
                UPDATE work_sessions
                SET paused_at = NOW()
                WHERE id = :id AND employee_id = :eid
            ");
            $stmt->execute([
                ':id' => $open['id'],
                ':eid' => $employeeId,
            ]);
            redirect('/gopools/public/employees/my_work.php');
        }
    }

    if ($action === 'resume') {
        if (!$open) {
            $errors[] = 'No active session found.';
        } elseif (empty($open['paused_at'])) {
            $errors[] = 'Session is not paused.';
        } else {
            $pausedAt = new DateTime($open['paused_at'], new DateTimeZone('Europe/Athens'));
            $now = new DateTime('now', new DateTimeZone('Europe/Athens'));
            $pauseMinutes = (int)floor(($now->getTimestamp() - $pausedAt->getTimestamp()) / 60);
            if ($pauseMinutes < 0) $pauseMinutes = 0;

            $stmt = $pdo->prepare("
                UPDATE work_sessions
                SET pause_minutes_total = pause_minutes_total + :mins,
                    paused_at = NULL
                WHERE id = :id AND employee_id = :eid
            ");
            $stmt->execute([
                ':mins' => $pauseMinutes,
                ':id' => $open['id'],
                ':eid' => $employeeId,
            ]);
            redirect('/gopools/public/employees/my_work.php');
        }
    }

    if ($action === 'stop') {
        if (!$open) {
            $errors[] = 'No active session to stop.';
        } else {
            $start = new DateTime($open['start_time'], new DateTimeZone('Europe/Athens'));
            $now = new DateTime('now', new DateTimeZone('Europe/Athens'));

            $pauseMinutesTotal = (int)$open['pause_minutes_total'];

            if (!empty($open['paused_at'])) {
                $pausedAt = new DateTime($open['paused_at'], new DateTimeZone('Europe/Athens'));
                $extraPaused = (int)floor(($now->getTimestamp() - $pausedAt->getTimestamp()) / 60);
                if ($extraPaused > 0) $pauseMinutesTotal += $extraPaused;
            }

            $durationMinutes = (int)floor(($now->getTimestamp() - $start->getTimestamp()) / 60) - $pauseMinutesTotal;
            if ($durationMinutes < 0) $durationMinutes = 0;

            $stmt = $pdo->prepare("
                UPDATE work_sessions
                SET end_time = NOW(),
                    duration_minutes = :dur,
                    pause_minutes_total = :pause_total,
                    paused_at = NULL
                WHERE id = :id AND employee_id = :eid
            ");
            $stmt->execute([
                ':dur' => $durationMinutes,
                ':pause_total' => $pauseMinutesTotal,
                ':id' => $open['id'],
                ':eid' => $employeeId,
            ]);
            redirect('/gopools/public/employees/my_work.php');
        }
    }

    if ($action === 'add_note') {
        if (!$open) {
            $errors[] = 'Start work first.';
        } else {
            $note = trim($_POST['note_text'] ?? '');
            if ($note === '') {
                $errors[] = 'Note cannot be empty.';
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO work_session_notes (work_session_id, note_text)
                    VALUES (:sid, :txt)
                ");
                $stmt->execute([
                    ':sid' => $open['id'],
                    ':txt' => $note,
                ]);
                redirect('/gopools/public/employees/my_work.php');
            }
        }
    }

    if ($action === 'upload_photo') {
        $isAjax = !empty($_POST['_ajax']);
        if (!$open) {
            if ($isAjax) { header('Content-Type: application/json'); echo json_encode(['ok'=>false,'error'=>'Start work first.']); exit; }
            $errors[] = 'Start work first.';
        } elseif (!isset($_FILES['photo']) || $_FILES['photo']['error'] !== UPLOAD_ERR_OK) {
            if ($isAjax) { header('Content-Type: application/json'); echo json_encode(['ok'=>false,'error'=>'Upload error: ' . ($_FILES['photo']['error'] ?? 'no file')]); exit; }
            $errors[] = 'Photo upload failed.';
        } else {
            $maxMb = (int)gp_setting($pdo, 'work_photo_max_mb', '8');
            $maxBytes = $maxMb * 1024 * 1024;
            $file = $_FILES['photo'];

            if ((int)$file['size'] > $maxBytes) {
                if ($isAjax) { header('Content-Type: application/json'); echo json_encode(['ok'=>false,'error'=>'Photo too large (max '.$maxMb.'MB).']); exit; }
                $errors[] = 'Photo is too large.';
            } else {
                $finfo = new finfo(FILEINFO_MIME_TYPE);
                $mime = (string)$finfo->file($file['tmp_name']);
                $allowed = [
                    'image/jpeg' => 'jpg',
                    'image/png'  => 'png',
                    'image/webp' => 'webp',
                ];

                if (!isset($allowed[$mime])) {
                    if ($isAjax) { header('Content-Type: application/json'); echo json_encode(['ok'=>false,'error'=>'Only JPG, PNG or WEBP allowed.']); exit; }
                    $errors[] = 'Only JPG, PNG or WEBP are allowed.';
                } else {
                    $ext = $allowed[$mime];
                    $newName = 'ws_' . (int)$open['id'] . '_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
                    $target = rtrim($uploadDirFs, '/\\') . DIRECTORY_SEPARATOR . $newName;

                    if (!move_uploaded_file($file['tmp_name'], $target)) {
                        if ($isAjax) { header('Content-Type: application/json'); echo json_encode(['ok'=>false,'error'=>'Could not save photo.']); exit; }
                        $errors[] = 'Could not save photo.';
                    } else {
                        $webPath = rtrim($uploadDirWeb, '/') . '/' . $newName;
                        $stmt = $pdo->prepare("
                            INSERT INTO work_session_photos
                                (work_session_id, file_path, original_name, mime_type, file_size)
                            VALUES
                                (:sid, :path, :orig, :mime, :size)
                        ");
                        $stmt->execute([
                            ':sid'  => $open['id'],
                            ':path' => $webPath,
                            ':orig' => basename((string)$file['name']),
                            ':mime' => $mime,
                            ':size' => (int)$file['size'],
                        ]);
                        if ($isAjax) { header('Content-Type: application/json'); echo json_encode(['ok'=>true]); exit; }
                        redirect('/gopools/public/employees/my_work.php');
                    }
                }
            }
        }
    }
}

$open = gp_get_open_session($pdo, $employeeId);

$sessionNotes = [];
$sessionPhotos = [];
$openShiftAlert = '';
if ($open) {
    $stmt = $pdo->prepare("SELECT * FROM work_session_notes WHERE work_session_id = :sid ORDER BY created_at DESC, id DESC");
    $stmt->execute([':sid' => $open['id']]);
    $sessionNotes = $stmt->fetchAll();

    $stmt = $pdo->prepare("SELECT * FROM work_session_photos WHERE work_session_id = :sid ORDER BY created_at DESC, id DESC");
    $stmt->execute([':sid' => $open['id']]);
    $sessionPhotos = $stmt->fetchAll();

    $start = new DateTime($open['start_time'], new DateTimeZone('Europe/Athens'));
    $now = new DateTime('now', new DateTimeZone('Europe/Athens'));
    $hoursOpen = ($now->getTimestamp() - $start->getTimestamp()) / 3600;
    $reminderHours = (int)gp_setting($pdo, 'open_shift_reminder_hours', '10');
    if ($hoursOpen >= $reminderHours) {
        $openShiftAlert = 'Open shift reminder: this session has been open for more than ' . $reminderHours . ' hours.';
    }
}

$monthStart = (new DateTime('first day of this month', new DateTimeZone('Europe/Athens')))->setTime(0,0,0);
$monthEnd = (clone $monthStart)->modify('+1 month');

$stmt = $pdo->prepare("
    SELECT COALESCE(SUM(duration_minutes), 0)
    FROM work_sessions
    WHERE employee_id = :eid
      AND duration_minutes IS NOT NULL
      AND start_time >= :d1
      AND start_time < :d2
");
$stmt->execute([
    ':eid' => $employeeId,
    ':d1' => $monthStart->format('Y-m-d H:i:s'),
    ':d2' => $monthEnd->format('Y-m-d H:i:s'),
]);
$monthMinutes = (int)$stmt->fetchColumn();
$monthHours = round($monthMinutes / 60, 1);

$stmt = $pdo->prepare("
    SELECT ws.*, p.code AS project_code, p.title AS project_title
    FROM work_sessions ws
    LEFT JOIN projects p ON p.id = ws.project_id
    WHERE ws.employee_id = :eid
    ORDER BY ws.start_time DESC
    LIMIT 20
");
$stmt->execute([':eid' => $employeeId]);
$recent = $stmt->fetchAll();

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1>My work</h1>
    <span><?php echo h($employee['full_name']); ?> 路 work tracking</span>
  </div>
</div>

<div class="grid-2" style="margin-bottom:14px">
  <div class="card">
    <div class="small">Hours this month</div>
    <div style="font-size:2rem;font-weight:700"><?php echo h($monthHours); ?> h</div>
  </div>
  <div class="card">
    <div class="small">Current status</div>
    <div style="font-size:1.2rem;font-weight:700">
      <?php echo $open ? (!empty($open['paused_at']) ? 'Paused' : 'Working') : 'Idle'; ?>
    </div>
    <?php if ($open): ?>
      <div class="small" style="margin-top:6px">
        Since <?php echo h($open['start_time']); ?>
        <?php if (!empty($open['project_code'])): ?>
          路 <?php echo h($open['project_code'] . ' 路 ' . $open['project_title']); ?>
        <?php endif; ?>
      </div>
    <?php endif; ?>
  </div>
</div>

<?php if ($openShiftAlert): ?>
  <div class="alert-danger" style="margin-bottom:14px"><?php echo h($openShiftAlert); ?></div>
<?php endif; ?>

<?php if ($errors): ?>
  <div class="alert-danger" style="margin-bottom:14px"><?php echo h(implode(' ', $errors)); ?></div>
<?php endif; ?>

<div class="card" style="margin-bottom:14px">
  <div class="page-header-title">
    <h1 style="font-size:1.1rem">Start / Stop / Pause</h1>
    <span>Worker control panel</span>
  </div>

  <?php if (!$open): ?>
    <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">
            <option value="0">General (no project)</option>
            <?php foreach ($projects as $p): ?>
              <option value="<?php echo (int)$p['id']; ?>">
                <?php echo h($p['code'] . ' 路 ' . $p['title']); ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="form-group">
          <label>Start notes</label>
          <input type="text" name="notes" placeholder="Optional start note">
        </div>
      </div>
      <div class="form-actions">
        <button class="btn btn-primary" type="submit">Start work</button>
      </div>
    </form>
  <?php else: ?>
    <div class="form-actions">
      <?php if (empty($open['paused_at'])): ?>
        <form method="post">
      <?php echo csrf_field(); ?>
          <input type="hidden" name="action" value="pause">
          <button class="btn btn-secondary" type="submit">Pause</button>
        </form>
      <?php else: ?>
        <form method="post">
      <?php echo csrf_field(); ?>
          <input type="hidden" name="action" value="resume">
          <button class="btn btn-primary" type="submit">Resume</button>
        </form>
      <?php endif; ?>

      <form method="post">
      <?php echo csrf_field(); ?>
        <input type="hidden" name="action" value="stop">
        <button class="btn btn-danger" type="submit">Stop work</button>
      </form>
    </div>

    <div class="grid-2" style="margin-top:14px">
      <div class="card">
        <div class="page-header-title">
          <h1 style="font-size:1rem">Add note</h1>
          <span>Live note during session</span>
        </div>
        <form method="post">
      <?php echo csrf_field(); ?>
          <input type="hidden" name="action" value="add_note">
          <div class="form-group">
            <label>Note</label>
            <textarea name="note_text" placeholder="What did you do?"></textarea>
          </div>
          <div class="form-actions">
            <button class="btn btn-primary btn-sm" type="submit">Save note</button>
          </div>
        </form>
      </div>

      <div class="card">
        <div class="page-header-title">
          <h1 style="font-size:1rem">???遖s礱 F?t???af???</h1>
          <span>Attach on-site evidence</span>
        </div>
        <div style="display:flex;flex-direction:column;gap:.5rem;">
          <select id="work-photo-category" style="font-size:.85rem;padding:.3rem .5rem;">
            <option value="pool">螤喂蟽委谓伪</option>
            <option value="mechanical">螠畏蠂伪谓慰蟽蟿维蟽喂慰</option>
          </select>
          <input type="file" id="work-photo-input" accept="image/*" multiple style="font-size:.85rem;">
          <button type="button" id="work-photo-btn" class="btn btn-primary btn-sm">???遖s礱 F?t???af???</button>
          <div id="work-photo-feedback" style="display:none;font-size:.8rem;font-weight:600;"></div>
        </div>
      </div>
    </div>

    <div class="grid-2" style="margin-top:14px">
      <div class="card">
        <div class="page-header-title">
          <h1 style="font-size:1rem">Session notes</h1>
        </div>
        <?php if (!$sessionNotes): ?>
          <p class="small">No notes yet.</p>
        <?php else: ?>
          <?php foreach ($sessionNotes as $n): ?>
            <div style="padding:8px 0;border-bottom:1px solid var(--border)">
              <div><?php echo nl2br(h($n['note_text'])); ?></div>
              <div class="small"><?php echo h($n['created_at']); ?></div>
            </div>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>

      <div class="card">
        <div class="page-header-title">
          <h1 style="font-size:1rem">Session photos</h1>
        </div>
        <?php if (!$sessionPhotos): ?>
          <p class="small">No photos yet.</p>
        <?php else: ?>
          <div style="display:flex;flex-wrap:wrap;gap:10px">
            <?php foreach ($sessionPhotos as $ph): ?>
              <a href="<?php echo h($ph['file_path']); ?>" target="_blank" rel="noopener">
                <img src="<?php echo h($ph['file_path']); ?>" alt="photo" style="width:96px;height:96px;object-fit:cover;border-radius:10px;border:1px solid var(--border)">
              </a>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>
    </div>
  <?php endif; ?>
</div>

<div class="card">
  <div class="page-header-title">
    <h1 style="font-size:1.1rem">Recent sessions</h1>
    <span>Last 20 sessions</span>
  </div>
  <div class="table-responsive">
    <table class="table">
      <thead>
        <tr>
          <th>Start</th>
          <th>End</th>
          <th>Duration</th>
          <th>Project</th>
          <th>Pause mins</th>
          <th>Notes</th>
        </tr>
      </thead>
      <tbody>
      <?php foreach ($recent as $r): ?>
        <tr>
          <td><?php echo h($r['start_time']); ?></td>
          <td><?php echo h($r['end_time']); ?></td>
          <td>
            <?php
              if ($r['duration_minutes'] === null) echo '<span class="badge">Active</span>';
              else {
                $h = floor(((int)$r['duration_minutes']) / 60);
                $m = ((int)$r['duration_minutes']) % 60;
                echo h(sprintf('%dh %02dmin', $h, $m));
              }
            ?>
          </td>
          <td>
            <?php echo $r['project_id'] ? h(($r['project_code'] ?? '') . ' 路 ' . ($r['project_title'] ?? '')) : 'General'; ?>
          </td>
          <td><?php echo (int)$r['pause_minutes_total']; ?></td>
          <td><?php echo h($r['notes']); ?></td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

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

<?php if ($open): ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
  var btn = document.getElementById('work-photo-btn');
  var fileInput = document.getElementById('work-photo-input');
  var fb = document.getElementById('work-photo-feedback');

  if (!btn || !fileInput) return;

  btn.addEventListener('click', async function() {
    var files = fileInput.files;
    if (!files || files.length === 0) { alert('\u0395\u03c0\u03b9\u03bb\u03ad\u03be\u03c4\u03b5 \u03c4\u03bf\u03c5\u03bb\u03ac\u03c7\u03b9\u03c3\u03c4\u03bf\u03bd \u03bc\u03af\u03b1 \u03c6\u03c9\u03c4\u03bf\u03b3\u03c1\u03b1\u03c6\u03af\u03b1.'); return; }

    btn.disabled = true;
    fb.style.display = 'block';
    var successCount = 0; var failCount = 0;
    var lastError = '';

    for (var i = 0; i < files.length; i++) {
      fb.textContent = '\u0391\u03bd\u03ad\u03b2\u03b1\u03c3\u03bc\u03b1 ' + (i + 1) + ' \u03b1\u03c0\u03cc ' + files.length + '...';
      fb.style.color = 'var(--gp-primary, #2563eb)';
      var fd = new FormData();
      fd.append('photo', files[i]);
      fd.append('action', 'upload_photo');
      fd.append('_ajax', '1');
      fd.append('csrf_token', window.csrfToken || '<?php echo csrf_token(); ?>');
      try {
        var res = await fetch(window.location.href, { method: 'POST', body: fd }).then(r => r.json());
        if (res.ok) successCount++;
        else { failCount++; lastError = res.error || 'Error'; }
      } catch(err) { failCount++; lastError = 'Network error'; }
    }

    if (failCount === 0) {
      fb.textContent = '\u2705 ' + successCount + ' \u03c6\u03c9\u03c4\u03bf\u03b3\u03c1\u03b1\u03c6\u03af\u03b5\u03c2 \u03b1\u03bd\u03ad\u03b2\u03b7\u03ba\u03b1\u03bd!';
      fb.style.color = '#16a34a';
      setTimeout(function() { window.location.reload(); }, 1000);
    } else if (successCount > 0) {
      fb.textContent = '\u26a0\ufe0f ' + successCount + ' \u03b5\u03c0\u03b9\u03c4\u03c5\u03c7\u03af\u03b1, ' + failCount + ' \u03b1\u03c0\u03bf\u03c4\u03c5\u03c7\u03af\u03b1.';
      fb.style.color = '#f59e0b';
      btn.disabled = false;
    } else {
      fb.textContent = '\u274c ' + lastError;
      fb.style.color = '#dc2626';
      btn.disabled = false;
    }
  });
});
</script>
<?php endif; ?>
