<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
require_once __DIR__ . '/../../app/core/i18n.php';
auth_require_login();
$pdo = crm_pdo();
$page_title = 'Project Statuses';

if (!gp_can_manage_project_access($pdo)) {
    http_response_code(403);
    exit('Access denied.');
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    gp_require_csrf();
    $action = trim((string)($_POST['action'] ?? 'save'));

    if ($action === 'save') {
        $id = (int)($_POST['id'] ?? 0);
        $statusKey = trim((string)($_POST['status_key'] ?? ''));
        $labelEl = trim((string)($_POST['label_el'] ?? ''));
        $labelEn = trim((string)($_POST['label_en'] ?? ''));
        $sortOrder = (int)($_POST['sort_order'] ?? 100);
        $isΕνεργό = isset($_POST['is_active']) ? 1 : 0;

        if ($statusKey === '') $errors[] = 'status_key is required.';
        if (!preg_match('/^[a-z0-9_\\-]+$/', $statusKey)) $errors[] = 'status_key must contain only lowercase letters, numbers, underscore or dash.';
        if ($labelEl === '') $errors[] = 'Greek label is required.';
        if ($labelEn === '') $errors[] = 'English label is required.';

        if (!$errors) {
            if ($id > 0) {
                $stmt = $pdo->prepare("
                    UPDATE project_statuses
                    SET status_key = :status_key, label_el = :label_el, label_en = :label_en, sort_order = :sort_order, is_active = :is_active
                    WHERE id = :id
                ");
                $stmt->execute([
                    ':status_key' => $statusKey,
                    ':label_el' => $labelEl,
                    ':label_en' => $labelEn,
                    ':sort_order' => $sortOrder,
                    ':is_active' => $isΕνεργό,
                    ':id' => $id,
                ]);
                $ok = 'Status updated.';
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO project_statuses (status_key, label_el, label_en, sort_order, is_active)
                    VALUES (:status_key, :label_el, :label_en, :sort_order, :is_active)
                ");
                $stmt->execute([
                    ':status_key' => $statusKey,
                    ':label_el' => $labelEl,
                    ':label_en' => $labelEn,
                    ':sort_order' => $sortOrder,
                    ':is_active' => $isΕνεργό,
                ]);
                $ok = 'Status added.';
            }
        }
    }

    if ($action === 'toggle') {
        $id = (int)($_POST['id'] ?? 0);
        $stmt = $pdo->prepare("UPDATE project_statuses SET is_active = CASE WHEN is_active = 1 THEN 0 ELSE 1 END WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $ok = 'Status updated.';
    }
}

$editId = (int)($_GET['edit_id'] ?? 0);
$editRow = null;
if ($editId > 0) {
    $stmt = $pdo->prepare("SELECT * FROM project_statuses WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => $editId]);
    $editRow = $stmt->fetch();
}

$rows = $pdo->query("SELECT * FROM project_statuses ORDER BY sort_order ASC, id ASC")->fetchAll();

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1><?php echo h(gp_tr($pdo, 'project_statuses')); ?></h1>
    <span>Μόνο για διαχειριστές</span>
  </div>
</div>

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

    <div class="page-header-title">
      <h1 style="font-size:1.05rem"><?php echo h(gp_tr($pdo, 'add_status')); ?></h1>
      <span>Δημιουργία ή επεξεργασία καταστάσεων</span>
    </div>

    <form method="post">
      <?php echo csrf_field(); ?>
      <input type="hidden" name="action" value="save">
      <input type="hidden" name="id" value="<?php echo (int)($editRow['id'] ?? 0); ?>">
      <div class="form-grid">
        <div class="form-group"><label>Κωδικός</label><input name="status_key" value="<?php echo h($editRow['status_key'] ?? ''); ?>" placeholder="waiting_installation"></div>
        <div class="form-group"><label>Ετικέτα (ΕΛ)</label><input name="label_el" value="<?php echo h($editRow['label_el'] ?? ''); ?>"></div>
        <div class="form-group"><label>Ετικέτα (EN)</label><input name="label_en" value="<?php echo h($editRow['label_en'] ?? ''); ?>"></div>
        <div class="form-group"><label>Σειρά</label><input type="number" name="sort_order" value="<?php echo h($editRow['sort_order'] ?? '100'); ?>"></div>
        <div class="form-group">
          <label style="display:flex;align-items:center;gap:8px;margin-top:28px">
            <input type="checkbox" name="is_active" <?php echo !isset($editRow['is_active']) || (int)$editRow['is_active'] === 1 ? 'checked' : ''; ?>>
            Ενεργό
          </label>
        </div>
      </div>
      <div class="form-actions">
        <button class="btn btn-primary" type="submit">Αποθήκευση</button>
        <?php if ($editRow): ?><a class="btn btn-secondary" href="/gopools/public/settings/project_statuses.php">Ακύρωση</a><?php endif; ?>
      </div>
    </form>
  </div>

  <div class="card">
    <div class="page-header-title">
      <h1 style="font-size:1.05rem">Status list</h1>
      <span>Dynamic statuses used by projects</span>
    </div>

    <div class="table-responsive">
      <table class="table">
        <thead><tr><th>Κωδικός</th><th>ΕΛ</th><th>EN</th><th>Σειρά</th><th>Ενεργό</th><th></th></tr></thead>
        <tbody>
          <?php foreach ($rows as $r): ?>
            <tr>
              <td><?php echo h($r['status_key']); ?></td>
              <td><?php echo h($r['label_el']); ?></td>
              <td><?php echo h($r['label_en']); ?></td>
              <td><?php echo (int)$r['sort_order']; ?></td>
              <td><?php echo (int)$r['is_active'] === 1 ? 'Ναι' : 'Όχι'; ?></td>
              <td>
                <div class="form-actions" style="margin-top:0">
                  <a class="btn btn-sm btn-outline-light" href="/gopools/public/settings/project_statuses.php?edit_id=<?php echo (int)$r['id']; ?>">Επεξεργασία</a>
                  <form method="post" style="display:inline">
      <?php echo csrf_field(); ?>
                    <input type="hidden" name="action" value="toggle">
                    <input type="hidden" name="id" value="<?php echo (int)$r['id']; ?>">
                    <button class="btn btn-sm btn-outline-light" type="submit"><?php echo (int)$r['is_active'] === 1 ? 'Απενεργοποίηση' : 'Ενεργοποίηση'; ?></button>
                  </form>
                </div>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
