<?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 = '/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') {
    $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('/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('/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('/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('/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('/public/employees/my_work.php');
            }
        }
    }

    if ($action === 'upload_photo') {
        if (!$open) {
            $errors[] = 'Start work first.';
        } elseif (!isset($_FILES['photo']) || $_FILES['photo']['error'] !== UPLOAD_ERR_OK) {
            $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) {
                $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])) {
                    $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)) {
                        $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'],
                        ]);
                        redirect('/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">
      <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">
          <input type="hidden" name="action" value="pause">
          <button class="btn btn-secondary" type="submit">Pause</button>
        </form>
      <?php else: ?>
        <form method="post">
          <input type="hidden" name="action" value="resume">
          <button class="btn btn-primary" type="submit">Resume</button>
        </form>
      <?php endif; ?>

      <form method="post">
        <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">
          <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">Upload photo</h1>
          <span>Attach on-site evidence</span>
        </div>
        <form method="post" enctype="multipart/form-data">
          <input type="hidden" name="action" value="upload_photo">
          <div class="form-group">
            <label>Photo</label>
            <input type="file" name="photo" accept="image/*" required>
          </div>
          <div class="form-actions">
            <button class="btn btn-primary btn-sm" type="submit">Upload photo</button>
          </div>
        </form>
      </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'; ?>
