<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
auth_require_login();

$pdo = crm_pdo();
$page_title = 'Employee';
if (!gp_is_full_project_access_role(gp_user_role($pdo))) {
    http_response_code(403);
    exit('Access denied.');
}

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

$item = [
    'code' => '',
    'full_name' => '',
    'phone' => '',
    'email' => '',
    'role_title' => '',
    'hourly_rate' => '',
    'hourly_rate_local' => '',
    'hourly_rate_outstation' => '',
    'daily_rate' => '',
    'notes' => '',
    'active' => 1,
];

$errors = [];
$ok = isset($_GET['saved']) && $_GET['saved'] === '1';

if ($id > 0) {
    $stmt = $pdo->prepare("
        SELECT
            id, code, full_name, phone, email, role_title,
            hourly_rate, hourly_rate_local, hourly_rate_outstation,
            daily_rate, notes, active
        FROM employees
        WHERE id = :id
        LIMIT 1
    ");
    $stmt->execute([':id' => $id]);
    $row = $stmt->fetch();
    if (!$row) {
        exit('Employee not found.');
    }
    $item = array_merge($item, $row);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    gp_require_csrf();
    $id = (int)($_POST['id'] ?? 0);

    foreach (array_keys($item) as $k) {
        if ($k === 'active') {
            $item[$k] = isset($_POST['active']) ? 1 : 0;
        } else {
            $item[$k] = trim((string)($_POST[$k] ?? ''));
        }
    }

    if ($item['full_name'] === '') $errors[] = 'Full name is required.';

    $hourlyRate = $item['hourly_rate'] !== '' ? (float)$item['hourly_rate'] : 0.0;
    $hourlyRateLocal = $item['hourly_rate_local'] !== '' ? (float)$item['hourly_rate_local'] : 0.0;
    $hourlyRateOutstation = $item['hourly_rate_outstation'] !== '' ? (float)$item['hourly_rate_outstation'] : 0.0;
    $dailyRate = $item['daily_rate'] !== '' ? (float)$item['daily_rate'] : 0.0;

    if (!$errors) {
        if ($id > 0) {
            $sql = "
                UPDATE employees
                SET code = :code,
                    full_name = :full_name,
                    phone = :phone,
                    email = :email,
                    role_title = :role_title,
                    hourly_rate = :hourly_rate,
                    hourly_rate_local = :hourly_rate_local,
                    hourly_rate_outstation = :hourly_rate_outstation,
                    daily_rate = :daily_rate,
                    notes = :notes,
                    active = :active
                WHERE id = :id
            ";
        } else {
            $sql = "
                INSERT INTO employees
                    (code, full_name, phone, email, role_title, hourly_rate, hourly_rate_local, hourly_rate_outstation, daily_rate, notes, active)
                VALUES
                    (:code, :full_name, :phone, :email, :role_title, :hourly_rate, :hourly_rate_local, :hourly_rate_outstation, :daily_rate, :notes, :active)
            ";
        }

        $params = [
            ':code' => $item['code'] !== '' ? $item['code'] : null,
            ':full_name' => $item['full_name'],
            ':phone' => $item['phone'] !== '' ? $item['phone'] : null,
            ':email' => $item['email'] !== '' ? $item['email'] : null,
            ':role_title' => $item['role_title'] !== '' ? $item['role_title'] : null,
            ':hourly_rate' => $hourlyRate,
            ':hourly_rate_local' => $hourlyRateLocal,
            ':hourly_rate_outstation' => $hourlyRateOutstation,
            ':daily_rate' => $dailyRate,
            ':notes' => $item['notes'] !== '' ? $item['notes'] : null,
            ':active' => (int)$item['active'],
        ];
        if ($id > 0) $params[':id'] = $id;

        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);

        if ($id === 0) $id = (int)$pdo->lastInsertId();
        header('Location: /gopools/public/employees/edit.php?id=' . $id . '&saved=1');
        exit;
    }
}

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1><?php echo $id > 0 ? 'Edit employee' : 'New employee'; ?></h1>
  </div>
</div>

<div class="card">
  <?php if ($ok): ?>
    <div class="alert-success">Employee saved successfully.</div>
  <?php endif; ?>
  <?php if ($errors): ?>
    <div class="alert-danger"><?php echo h(implode(' ', $errors)); ?></div>
  <?php endif; ?>

  <form method="post">
      <?php echo csrf_field(); ?>
    <input type="hidden" name="id" value="<?php echo (int)$id; ?>">

    <div class="form-grid">
      <div class="form-group">
        <label>Code</label>
        <input type="text" name="code" value="<?php echo h($item['code']); ?>">
      </div>

      <div class="form-group">
        <label>Full name</label>
        <input type="text" name="full_name" value="<?php echo h($item['full_name']); ?>">
      </div>

      <div class="form-group">
        <label>Phone</label>
        <input type="text" name="phone" value="<?php echo h($item['phone']); ?>">
      </div>

      <div class="form-group">
        <label>Email</label>
        <input type="email" name="email" value="<?php echo h($item['email']); ?>">
      </div>

      <div class="form-group">
        <label>Role title</label>
        <input type="text" name="role_title" value="<?php echo h($item['role_title']); ?>">
      </div>

      <div class="form-group">
        <label>Hourly rate (legacy)</label>
        <input type="number" step="0.01" min="0" name="hourly_rate" value="<?php echo h((string)$item['hourly_rate']); ?>">
      </div>

      <div class="form-group">
        <label>Hourly rate local (εντός)</label>
        <input type="number" step="0.01" min="0" name="hourly_rate_local" value="<?php echo h((string)$item['hourly_rate_local']); ?>">
      </div>

      <div class="form-group">
        <label>Hourly rate outstation (εκτός)</label>
        <input type="number" step="0.01" min="0" name="hourly_rate_outstation" value="<?php echo h((string)$item['hourly_rate_outstation']); ?>">
      </div>

      <div class="form-group">
        <label>Daily rate</label>
        <input type="number" step="0.01" min="0" name="daily_rate" value="<?php echo h((string)$item['daily_rate']); ?>">
      </div>

      <div class="form-group">
        <label style="display:flex;align-items:center;gap:8px;margin-top:28px">
          <input type="checkbox" name="active" <?php echo (int)$item['active'] === 1 ? 'checked' : ''; ?>>
          Active
        </label>
      </div>

      <div class="form-group" style="grid-column:1/-1">
        <label>Notes</label>
        <textarea name="notes"><?php echo h($item['notes']); ?></textarea>
      </div>
    </div>

    <div class="form-actions">
      <button class="btn btn-primary" type="submit">Save</button>
      <a class="btn btn-secondary" href="/gopools/public/employees/index.php">Cancel</a>
    </div>
  </form>
</div>

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