<?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 = :uid
    LIMIT 1
");
$stmt->execute([':id' => $assignmentId, ':uid' => $userId]);
$item = $stmt->fetch();
if (!$item) die('Assignment not found.');

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $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.';
        } 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 = '/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 = :uid
            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="/public/employees/my_jobs.php">Back to My Jobs</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>Project code:</strong> <?php echo h($item['code']); ?></p>
    <p><strong>Customer:</strong> <?php echo h($item['customer_name']); ?></p>
    <p><strong>Customer phone:</strong> <?php echo h($item['customer_phone']); ?></p>
    <p><strong>Address:</strong> <?php echo h(trim(($item['address'] ?? '') . ' ' . ($item['city'] ?? ''))); ?></p>
    <p><strong>Role:</strong> <?php echo h($item['role_label']); ?></p>
    <p><strong>Status:</strong> <?php echo h($item['status']); ?></p>
    <p><strong>Project notes:</strong> <?php echo nl2br(h($item['project_notes'] ?? '')); ?></p>

    <form method="post" enctype="multipart/form-data">
      <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>Employee note</label>
          <textarea name="employee_note"><?php echo h($item['employee_note']); ?></textarea>
        </div>
        <div class="form-group">
          <label>Checklist done</label>
          <div><input type="checkbox" name="checklist_done" <?php echo ((int)$item['checklist_done'] === 1) ? 'checked' : ''; ?>></div>
        </div>
        <div class="form-group">
          <label>Upload photo</label>
          <input type="file" name="job_photo" accept="image/*">
        </div>
      </div>

      <div class="form-actions">
        <button class="btn btn-secondary" type="submit" name="action" value="save">Save</button>
        <button class="btn btn-primary" type="submit" name="action" value="start">Start Job</button>
        <button class="btn btn-primary" type="submit" name="action" value="stop">Complete Job</button>
      </div>
    </form>
  </div>

  <div class="card">
    <div class="page-header-title">
      <h1 style="font-size:1.05rem">Job photos</h1>
      <span>Uploaded from employee portal</span>
    </div>

    <?php if (!$photos): ?>
      <p class="small">No uploaded photos yet.</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>Started at:</strong> <?php echo h($item['started_at']); ?></p>
      <p><strong>Stopped at:</strong> <?php echo h($item['stopped_at']); ?></p>
    </div>
  </div>
</div>

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