<?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') {
    $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);
        $isActive = 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' => $isActive,
                    ':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' => $isActive,
                ]);
                $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>Admin only</span>
  </div>
</div>

<div class="grid-2">
  <div class="card">
    <?php if ($ok): ?><div class="alert-danger" style="background:rgba(22,163,74,.15);color:#166534;border-color:rgba(22,163,74,.25)"><?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>Create or edit project statuses</span>
    </div>

    <form method="post">
      <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>Status key</label><input name="status_key" value="<?php echo h($editRow['status_key'] ?? ''); ?>" placeholder="waiting_installation"></div>
        <div class="form-group"><label>Label EL</label><input name="label_el" value="<?php echo h($editRow['label_el'] ?? ''); ?>"></div>
        <div class="form-group"><label>Label EN</label><input name="label_en" value="<?php echo h($editRow['label_en'] ?? ''); ?>"></div>
        <div class="form-group"><label>Sort order</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' : ''; ?>>
            Active
          </label>
        </div>
      </div>
      <div class="form-actions">
        <button class="btn btn-primary" type="submit">Save status</button>
        <?php if ($editRow): ?><a class="btn btn-secondary" href="/public/settings/project_statuses.php">Cancel</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>Key</th><th>EL</th><th>EN</th><th>Sort</th><th>Active</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 ? 'Yes' : 'No'; ?></td>
              <td>
                <div class="form-actions" style="margin-top:0">
                  <a class="btn btn-sm btn-outline-light" href="/public/settings/project_statuses.php?edit_id=<?php echo (int)$r['id']; ?>">Edit</a>
                  <form method="post" style="display:inline">
                    <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 ? 'Disable' : 'Enable'; ?></button>
                  </form>
                </div>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
