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

$user = auth_user();
$userId = (int)($user['id'] ?? 0);
$assignmentId = (int)($_GET['assignment_id'] ?? $_POST['assignment_id'] ?? 0);
if ($assignmentId <= 0) die('Missing assignment_id.');

$stmt = $pdo->prepare("
    SELECT pa.*, p.title, p.code, p.address, p.city, p.notes AS project_notes,
           c.name AS customer_name, c.phone AS customer_phone
    FROM project_assignments pa
    JOIN projects p ON p.id = pa.project_id
    LEFT JOIN customers c ON c.id = p.customer_id
    WHERE pa.id = :id
      AND pa.employee_id = (SELECT employee_id FROM users WHERE id = :uid LIMIT 1)
    LIMIT 1
");
$stmt->execute([':id' => $assignmentId, ':uid' => $userId]);
$item = $stmt->fetch();
if (!$item) die('? a???es? de? �?????e ? de? ??ete p??s�as?.');


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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    gp_require_csrf();
    $action = trim((string)($_POST['action'] ?? ''));
    $employeeNote = trim((string)($_POST['employee_note'] ?? ''));
    $gpsLat = trim((string)($_POST['gps_latitude'] ?? ''));
    $gpsLng = trim((string)($_POST['gps_longitude'] ?? ''));
    $checklistDone = isset($_POST['checklist_done']) ? 1 : 0;

    if ($gpsLat !== '' && !is_numeric($gpsLat)) $errors[] = 'Latitude must be numeric.';
    if ($gpsLng !== '' && !is_numeric($gpsLng)) $errors[] = 'Longitude must be numeric.';

    if (!$errors) {
        if ($action === 'start') {
            $stmt = $pdo->prepare("
                UPDATE project_assignments
                SET started_at = NOW(),
                    status = 'in_progress',
                    gps_latitude = :lat,
                    gps_longitude = :lng,
                    employee_note = :note,
                    checklist_done = :chk
                WHERE id = :id AND employee_id = :uid
            ");
            $stmt->execute([
                ':lat' => $gpsLat !== '' ? $gpsLat : null,
                ':lng' => $gpsLng !== '' ? $gpsLng : null,
                ':note' => $employeeNote !== '' ? $employeeNote : null,
                ':chk' => $checklistDone,
                ':id' => $assignmentId,
                ':uid' => $userId,
            ]);
            $ok = 'Job started.';
        } elseif ($action === 'stop') {
            $stmt = $pdo->prepare("
                UPDATE project_assignments
                SET stopped_at = NOW(),
                    status = 'completed',
                    gps_latitude = :lat,
                    gps_longitude = :lng,
                    employee_note = :note,
                    checklist_done = :chk
                WHERE id = :id AND employee_id = :uid
            ");
            $stmt->execute([
                ':lat' => $gpsLat !== '' ? $gpsLat : null,
                ':lng' => $gpsLng !== '' ? $gpsLng : null,
                ':note' => $employeeNote !== '' ? $employeeNote : null,
                ':chk' => $checklistDone,
                ':id' => $assignmentId,
                ':uid' => $userId,
            ]);
            $ok = 'Job completed.';
            gp_log_action($pdo, 'ASSIGNMENT_COMPLETE', 'project', $item['project_id'], "Ολοκληρώθηκε η εργασία από " . ($user['username'] ?? 'Employee') . " στο έργο " . $item['title']);
        } elseif ($action === 'save') {
            $stmt = $pdo->prepare("
                UPDATE project_assignments
                SET gps_latitude = :lat,
                    gps_longitude = :lng,
                    employee_note = :note,
                    checklist_done = :chk
                WHERE id = :id AND employee_id = :uid
            ");
            $stmt->execute([
                ':lat' => $gpsLat !== '' ? $gpsLat : null,
                ':lng' => $gpsLng !== '' ? $gpsLng : null,
                ':note' => $employeeNote !== '' ? $employeeNote : null,
                ':chk' => $checklistDone,
                ':id' => $assignmentId,
                ':uid' => $userId,
            ]);
            $ok = 'Job notes saved.';
        }

        if (!empty($_FILES['job_photo']['name']) && ($_FILES['job_photo']['error'] ?? 1) === 0) {
            $uploadDirFs = __DIR__ . '/../uploads/job_photos';
            $uploadDirWeb = '/gopools/public/uploads/job_photos';
            if (!is_dir($uploadDirFs)) @mkdir($uploadDirFs, 0775, True);

            $safeName = preg_replace('/[^A-Za-z0-9._-]/', '_', (string)$_FILES['job_photo']['name']);
            $stored = 'assignment_' . $assignmentId . '_' . time() . '_' . $safeName;
            $fullFs = rtrim($uploadDirFs, '/\\') . DIRECTORY_SEPARATOR . $stored;

            if (move_uploaded_file($_FILES['job_photo']['tmp_name'], $fullFs)) {
                $stmt = $pdo->prepare("
                    INSERT INTO employee_job_photos (project_assignment_id, file_name, file_path)
                    VALUES (:aid, :fname, :fpath)
                ");
                $stmt->execute([
                    ':aid' => $assignmentId,
                    ':fname' => $safeName,
                    ':fpath' => rtrim($uploadDirWeb, '/') . '/' . $stored,
                ]);
                if ($ok === '') $ok = 'Photo uploaded.';
                else $ok .= ' Photo uploaded.';
            }
        }

        $stmt = $pdo->prepare("
            SELECT pa.*, p.title, p.code, p.address, p.city, p.notes AS project_notes,
                   c.name AS customer_name, c.phone AS customer_phone
            FROM project_assignments pa
            JOIN projects p ON p.id = pa.project_id
            LEFT JOIN customers c ON c.id = p.customer_id
            WHERE pa.id = :id
              AND pa.employee_id = (SELECT employee_id FROM users WHERE id = :uid LIMIT 1)
            LIMIT 1
        ");
        $stmt->execute([':id' => $assignmentId, ':uid' => $userId]);
        $item = $stmt->fetch();
    }
}

$stmt = $pdo->prepare("SELECT * FROM employee_job_photos WHERE project_assignment_id = :aid ORDER BY uploaded_at DESC, id DESC");
$stmt->execute([':aid' => $assignmentId]);
$photos = $stmt->fetchAll();

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1><?php echo h($item['title']); ?></h1>
    <span><?php echo h($item['assigned_date'] . ' ' . substr((string)$item['assigned_time'], 0, 5)); ?></span>
  </div>
  <div class="page-header-actions">
    <a class="btn btn-secondary btn-sm" href="/gopools/public/employees/my_jobs.php">← Πίσω</a>
  </div>
</div>

<div class="grid-2">
  <div class="card">
    <?php if ($ok): ?><div class="alert-danger" style="background:rgba(22,163,74,.15);color:#bbf7d0;border-color:rgba(22,163,74,.35)"><?php echo h($ok); ?></div><?php endif; ?>
    <?php if ($errors): ?><div class="alert-danger"><?php echo h(implode(' ', $errors)); ?></div><?php endif; ?>

    <p><strong>Κωδικός Έργου:</strong> <?php echo h($item['code']); ?></p>
    <p><strong>Πελάτης:</strong> <?php echo h($item['customer_name']); ?></p>
    <p><strong>Τηλέφωνο:</strong> <?php echo h($item['customer_phone']); ?></p>
    <p><strong>Διεύθυνση:</strong> <?php echo h(trim(($item['address'] ?? '') . ' ' . ($item['city'] ?? ''))); ?></p>
    <p><strong>Ρόλος:</strong> <?php echo h($item['role_label']); ?></p>
    <p><strong>Κατάσταση:</strong> <?php echo h($item['status']); ?></p>
    <p><strong>Σημειώσεις Έργου:</strong> <?php echo nl2br(h($item['project_notes'] ?? '')); ?></p>

    <form method="post" enctype="multipart/form-data">
      <?php echo csrf_field(); ?>
      <input type="hidden" name="assignment_id" value="<?php echo (int)$assignmentId; ?>">

      <div class="form-grid">
        <div class="form-group">
          <label>GPS Latitude</label>
          <input type="text" name="gps_latitude" value="<?php echo h($item['gps_latitude']); ?>">
        </div>
        <div class="form-group">
          <label>GPS Longitude</label>
          <input type="text" name="gps_longitude" value="<?php echo h($item['gps_longitude']); ?>">
        </div>
        <div class="form-group" style="grid-column:1/-1">
          <label>Σημείωση Υπαλλήλου</label>
          <textarea name="employee_note"><?php echo h($item['employee_note']); ?></textarea>
        </div>
        <div class="form-group">
          <label>Ολοκλήρωση Καταλόγου</label>
          <div><input type="checkbox" name="checklist_done" <?php echo ((int)$item['checklist_done'] === 1) ? 'checked' : ''; ?>></div>
        </div>
        <div class="form-group">
          <label>Ανέβασμα Φωτογραφιών</label>
          <input type="file" name="job_photo" id="job-photo-input" accept="image/*" multiple>
          <div id="job-photo-progress" style="display:none;font-size:.8rem;font-weight:600;margin-top:.35rem;"></div>
        </div>
      </div>

      <div class="form-actions">
        <button class="btn btn-secondary" type="submit" name="action" value="save">Αποθήκευση</button>
        <button class="btn btn-primary" type="submit" name="action" value="start">Έναρξη Εργασίας</button>
        <button class="btn btn-primary" type="submit" name="action" value="stop">Ολοκλήρωση</button>
      </div>
    </form>
  </div>

  <div class="card" style="margin-bottom:24px;">
    <div class="page-header-title">
      <h1 style="font-size:1.05rem">📎 Προσφορά / Offer</h1>
      <span>Ανέβασμα προσφοράς για αυτήν την εργασία</span>
    </div>
    <div style="margin-top:16px;">
      <?php if (!empty($item['offer_filename'])): ?>
        <div style="margin-bottom:16px;padding:12px;background:rgba(16,185,129,0.1);border:1px solid rgba(16,185,129,0.3);border-radius:8px;">
          <strong>✅ Ανεβάστηκε:</strong> <a href="/gopools/public/uploads/project_offers/<?php echo h($item['offer_filename']); ?>" target="_blank" style="font-weight:700;color:var(--gp-primary);"><?php echo h($item['offer_filename']); ?></a>
        </div>
      <?php endif; ?>
      <form id="offer-upload-form">
        <?php echo csrf_field(); ?>
        <input type="hidden" name="assignment_id" value="<?php echo (int)$assignmentId; ?>">
        <input type="hidden" name="by_type" value="employee">
        <div style="display:flex;gap:12px;align-items:center;">
          <input type="file" name="offer_file" accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png" required style="font-size:0.85rem;flex:1;">
          <button type="submit" class="btn btn-sm btn-primary">Upload</button>
        </div>
        <div id="offer-feedback" style="display:none;margin-top:8px;font-size:0.85rem;font-weight:600;"></div>
      </form>
    </div>
  </div>

  <div class="card">
    <div class="page-header-title">
      <h1 style="font-size:1.05rem">📷 Φωτογραφίες Εργασίας</h1>
      <span>Ανεβασμένες από το πεδίο</span>
    </div>

    <?php if (!$photos): ?>
      <p class="small">Δεν έχουν ανεβαστεί φωτογραφίες ακόμα.</p>
    <?php else: ?>
      <div class="grid-2">
        <?php foreach ($photos as $p): ?>
          <div class="card" style="padding:8px">
            <img src="<?php echo h($p['file_path']); ?>" alt="" style="width:100%;height:180px;object-fit:cover;border-radius:10px">
            <div class="small" style="margin-top:6px"><?php echo h($p['file_name']); ?></div>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>

    <div style="margin-top:12px">
      <p><strong>Έναρξη:</strong> <?php echo h($item['started_at']); ?></p>
      <p><strong>Ολοκλήρωση:</strong> <?php echo h($item['stopped_at']); ?></p>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  var mainForm = document.querySelector('form[enctype="multipart/form-data"]');
  var photoInput = document.getElementById('job-photo-input');
  var progress = document.getElementById('job-photo-progress');
  if (!mainForm || !photoInput) return;

  mainForm.addEventListener('submit', async function(e) {
    var files = photoInput.files;
    if (!files || files.length <= 1) return;
    e.preventDefault();
    var assignmentId = mainForm.querySelector('input[name=assignment_id]').value;
    var csrfToken = mainForm.querySelector('input[name=csrf_token]').value;

    progress.style.display = 'block';
    progress.style.color = 'var(--gp-primary)';

    for (var i = 1; i < files.length; i++) {
      progress.textContent = 'Ανέβασμα φωτογραφίας ' + i + ' από ' + (files.length - 1) + '...';
      var fd = new FormData();
      fd.append('job_photo', files[i]);
      fd.append('assignment_id', assignmentId);
      fd.append('csrf_token', csrfToken);
      try {
        await fetch('/gopools/public/api/upload_job_photo.php', {method:'POST', body: fd});
      } catch(err) {}
    }

    // Now submit the main form via HTML submit
    mainForm.submit();
  });

  // Offer Upload Form
  var offerForm = document.getElementById('offer-upload-form');
  if (offerForm) {
    offerForm.addEventListener('submit', function(e) {
      e.preventDefault();
      var btn = offerForm.querySelector('button[type=submit]');
      var fb = document.getElementById('offer-feedback');
      btn.disabled = true; btn.textContent = 'Uploading...';
      var fd = new FormData(offerForm);
      fetch('/gopools/public/api/upload_assignment_offer.php', { method: 'POST', body: fd })
        .then(r => r.json())
        .then(res => {
          fb.style.display = 'block';
          if (res.ok) {
            fb.textContent = '✅ Προσφορά ανέβηκε επιτυχώς!';
            fb.style.color = '#10b981';
            setTimeout(() => window.location.reload(), 1000);
          } else {
            fb.textContent = '❌ ' + (res.error || 'Σφάλμα');
            fb.style.color = '#dc2626';
            btn.disabled = false; btn.textContent = 'Upload';
          }
        })
        .catch(() => {
          fb.style.display = 'block';
          fb.textContent = '❌ Network error.';
          fb.style.color = '#dc2626';
          btn.disabled = false; btn.textContent = 'Upload';
        });
    });
  }
});
</script>
<?php include __DIR__ . '/../includes/footer.php'; ?>
