<?php
require_once 'header.php';
require_permission('employees');

$search = trim($_GET['q'] ?? '');
$msg = trim($_GET['msg'] ?? '');
if ($msg !== '') {
  echo '<div class="alert alert-success mb-3">'.htmlspecialchars($msg).'</div>';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_employee'])) {
  $first = trim($_POST['first_name'] ?? '');
  $last  = trim($_POST['last_name'] ?? '');
  $job   = trim($_POST['job_title'] ?? '');
  $addr  = trim($_POST['address'] ?? '');
  $rate  = (float)str_replace(',', '.', ($_POST['hourly_rate'] ?? '0'));
  $active = isset($_POST['active']) ? 1 : 0;

  if ($first === '' || $last === '') {
    echo '<div class="alert alert-danger mb-3">Ime i prezime su obavezni.</div>';
  } else {
    $stmt = $mysqli->prepare("INSERT INTO employees (first_name,last_name,job_title,address,hourly_rate,active) VALUES (?,?,?,?,?,?)");
    $stmt->bind_param('ssssdi', $first, $last, $job, $addr, $rate, $active);
    $stmt->execute();
    $stmt->close();
    echo '<div class="alert alert-success mb-3">Djelatnik dodan.</div>';
  }
}

if (isset($_GET['toggle_id'])) {
  $id = (int)$_GET['toggle_id'];
  if ($id > 0) {
    $mysqli->query("UPDATE employees SET active = IF(active=1,0,1) WHERE id=".(int)$id);
    header('Location: employees.php?msg='.urlencode('Status promijenjen.'));
    exit;
  }
}

$where = '';
if ($search !== '') {
  $esc = $mysqli->real_escape_string($search);
  $where = "WHERE first_name LIKE '%{$esc}%' OR last_name LIKE '%{$esc}%' OR job_title LIKE '%{$esc}%'";
}
$res = $mysqli->query("SELECT * FROM employees {$where} ORDER BY id ASC, last_name, first_name");
?>
<div class="row g-3 mb-3 align-items-center">
  <div class="col">
    <div class="section-title">Djelatnici</div>
    <div class="text-muted small">Unos i izmjene djelatnika</div>
  </div>
</div>

<div class="row g-3">
  <div class="col-12 col-lg-4">
    <div class="card card-soft">
      <div class="card-header card-soft-header"><span class="fw-semibold">Novi djelatnik</span></div>
      <div class="card-body card-soft-body">
        <form method="post">
          <input type="hidden" name="create_employee" value="1">
          <div class="mb-2">
            <label class="form-label">Ime</label>
            <input class="form-control" name="first_name" required>
          </div>
          <div class="mb-2">
            <label class="form-label">Prezime</label>
            <input class="form-control" name="last_name" required>
          </div>
          <div class="mb-2">
            <label class="form-label">Radno mjesto</label>
            <input class="form-control" name="job_title" placeholder="npr. Monter">
          </div>
          <div class="mb-2">
            <label class="form-label">Adresa</label>
            <input class="form-control" name="address">
          </div>
          <div class="mb-2">
            <label class="form-label">Satnica (EUR/h)</label>
            <input class="form-control" name="hourly_rate" placeholder="npr. 8,50">
          </div>
          <div class="form-check mt-2">
            <input class="form-check-input" type="checkbox" name="active" id="emp_active" checked>
            <label class="form-check-label" for="emp_active">Aktivan</label>
          </div>
          <button class="btn btn-primary btn-soft w-100 mt-3" type="submit">Spremi djelatnika</button>
        </form>
      </div>
    </div>
  </div>

  <div class="col-12 col-lg-8">
    <div class="card card-soft">
      <div class="card-header card-soft-header d-flex justify-content-between align-items-center">
        <span class="fw-semibold">Popis djelatnika</span>
        <span class="pill-counter d-none d-sm-inline"><?php echo (int)$res->num_rows; ?> djelatnika</span>
      </div>
      <div class="card-body card-soft-body">
        <div class="mb-3">
          <form method="get" class="row g-2 align-items-end">
            <div class="col-12 col-md-6">
              <label class="form-label">Pretraga</label>
              <input class="form-control form-control-sm" name="q" value="<?php echo htmlspecialchars($search); ?>"
                     placeholder="ime, prezime ili radno mjesto...">
            </div>
            <div class="col-auto">
              <button class="btn btn-outline-primary btn-soft btn-sm" type="submit">Primijeni</button>
            </div>
            <?php if ($search !== ''): ?>
            <div class="col-auto">
              <a class="btn btn-outline-secondary btn-soft btn-sm" href="employees.php">Reset</a>
            </div>
            <?php endif; ?>
          </form>
        </div>

        <div class="table-responsive d-none d-md-block">
          <table class="table table-sm align-middle">
            <thead class="small text-muted">
              <tr>
                <th>Ime</th><th>Radno mjesto</th><th>Satnica</th><th>Status</th><th class="text-end">Akcije</th>
              </tr>
            </thead>
            <tbody>
            <?php while ($e = $res->fetch_assoc()): ?>
              <tr>
                <td class="fw-semibold"><?php echo htmlspecialchars($e['first_name'].' '.$e['last_name']); ?></td>
                <td><?php echo htmlspecialchars($e['job_title']); ?></td>
                <td><?php echo number_format((float)$e['hourly_rate'], 2, ',', '.'); ?> €</td>
                <td>
                  <?php if ((int)$e['active']===1): ?>
                    <span class="badge bg-success">Aktivan</span>
                  <?php else: ?>
                    <span class="badge bg-secondary">Neaktivan</span>
                  <?php endif; ?>
                </td>
                <td class="text-end">
                  <a class="btn btn-sm btn-outline-primary btn-soft" href="employee_edit.php?id=<?php echo $e['id']; ?>">Uredi</a>
                  <a class="btn btn-sm btn-outline-warning btn-soft"
                     href="employees.php?toggle_id=<?php echo $e['id']; ?>"
                     onclick="return confirm('Promijeniti status djelatnika?');">Status</a>
                </td>
              </tr>
            <?php endwhile; ?>
            </tbody>
          </table>
        </div>

        <div class="d-md-none">
          <?php
          $res->data_seek(0);
          if ($res->num_rows===0): ?>
            <div class="text-muted small">Nema djelatnika.</div>
          <?php endif; ?>
          <?php while ($e = $res->fetch_assoc()): ?>
            <div class="list-card">
              <div class="list-card-title"><?php echo htmlspecialchars($e['first_name'].' '.$e['last_name']); ?></div>
              <div class="list-card-sub"><?php echo htmlspecialchars($e['job_title']); ?></div>
              <div class="list-card-meta">
                Satnica: <?php echo number_format((float)$e['hourly_rate'], 2, ',', '.'); ?> € •
                <?php echo ((int)$e['active']===1)?'Aktivan':'Neaktivan'; ?>
              </div>
              <div class="d-flex justify-content-end gap-1 mt-2">
                <a class="btn btn-outline-primary btn-sm" href="employee_edit.php?id=<?php echo $e['id']; ?>">Uredi</a>
                <a class="btn btn-outline-warning btn-sm" href="employees.php?toggle_id=<?php echo $e['id']; ?>">Status</a>
              </div>
            </div>
          <?php endwhile; ?>
        </div>

      </div>
    </div>
  </div>
</div>

<?php require_once 'footer.php'; ?>
