<?php
// /api/towlens/templates.php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');

// Strict no-cache for APIs with config/meta
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

session_start();

$ROOT = realpath(__DIR__ . '/..');
if (!$ROOT) {
    http_response_code(500);
    echo json_encode(['error' => 'Server path resolution failed']);
    exit;
}

$config = require $ROOT . '/lib/config.php';
require $ROOT . '/lib/db.php';
require $ROOT . '/lib/helpers.php';

if (!($pdo instanceof PDO)) {
    http_response_code(500);
    echo json_encode(['error' => 'Database not available']);
    exit;
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

/**
 * AuthN + AuthZ
 * - Require normal app login
 * - Restrict to admins / org admins etc.
 */
require_admin_auth($config); // your existing function

$user = $_SESSION['user'] ?? [];
$role = $user['role'] ?? '';

if (!in_array($role, ['admin', 'org_admin'], true)) {
    http_response_code(403);
    echo json_encode(['error' => 'Forbidden']);
    exit;
}

/**
 * Optional: IP allowlist for extra defence in depth
 *
 * $allowedIps = $config['internal_ip_allowlist'] ?? [];
 * if ($allowedIps && !in_array($_SERVER['REMOTE_ADDR'] ?? '', $allowedIps, true)) {
 *     http_response_code(403);
 *     echo json_encode(['error' => 'Forbidden']);
 *     exit;
 * }
 */

/**
 * Ensure tables exist (idempotent, safe)
 * You can remove this in production once schema is migrated.
 */
$pdo->exec("
CREATE TABLE IF NOT EXISTS towlens_templates (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  code VARCHAR(50) NOT NULL UNIQUE,
  description VARCHAR(255) DEFAULT NULL,
  is_active TINYINT(1) NOT NULL DEFAULT 1,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

$pdo->exec("
CREATE TABLE IF NOT EXISTS towlens_template_steps (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  template_id INT UNSIGNED NOT NULL,
  step_order INT UNSIGNED NOT NULL,
  code VARCHAR(50) NOT NULL,
  label VARCHAR(150) NOT NULL,
  is_required TINYINT(1) NOT NULL DEFAULT 1,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT fk_towlens_steps_template
    FOREIGN KEY (template_id) REFERENCES towlens_templates(id)
    ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

function json_response($data, int $status = 200): void {
    http_response_code($status);
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
if ($method !== 'GET') {
    header('Allow: GET');
    json_response(['error' => 'Method not allowed'], 405);
}

$id           = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$includeSteps = isset($_GET['include_steps']) && $_GET['include_steps'] !== '0';

// Single template
if ($id > 0) {
    $stmt = $pdo->prepare("
        SELECT id, name, code, description, is_active, created_at
        FROM towlens_templates
        WHERE id = ?
    ");
    $stmt->execute([$id]);
    $tpl = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$tpl) {
        json_response(['error' => 'Template not found'], 404);
    }

    if ($includeSteps) {
        $stepsStmt = $pdo->prepare("
            SELECT id, step_order, code, label, is_required, created_at
            FROM towlens_template_steps
            WHERE template_id = ?
            ORDER BY step_order ASC, id ASC
        ");
        $stepsStmt->execute([$id]);
        $tpl['steps'] = $stepsStmt->fetchAll(PDO::FETCH_ASSOC);
    }

    json_response($tpl);
}

// List templates
$where  = [];
$params = [];

if (isset($_GET['active']) && $_GET['active'] === '1') {
    $where[] = "is_active = 1";
}

$sql = "
    SELECT id, name, code, description, is_active, created_at
    FROM towlens_templates
";
if ($where) {
    $sql .= " WHERE " . implode(" AND ", $where);
}
$sql .= " ORDER BY name ASC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$templates = $stmt->fetchAll(PDO::FETCH_ASSOC);

if ($includeSteps && $templates) {
    $ids = array_column($templates, 'id');
    if ($ids) {
        $in = implode(',', array_fill(0, count($ids), '?'));
        $stepsStmt = $pdo->prepare("
            SELECT id, template_id, step_order, code, label, is_required, created_at
            FROM towlens_template_steps
            WHERE template_id IN ($in)
            ORDER BY template_id ASC, step_order ASC, id ASC
        ");
        $stepsStmt->execute($ids);
        $steps = $stepsStmt->fetchAll(PDO::FETCH_ASSOC);

        $byTpl = [];
        foreach ($steps as $row) {
            $byTpl[$row['template_id']][] = $row;
        }

        foreach ($templates as &$tpl) {
            $tpl['steps'] = $byTpl[$tpl['id']] ?? [];
        }
        unset($tpl);
    }
}

json_response($templates);
