<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/middleware.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/functions.php';
require_admin();
header('Content-Type: application/json');

$pdo->exec("CREATE TABLE IF NOT EXISTS packages (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL UNIQUE,
  description TEXT,
  status TEXT NOT NULL DEFAULT 'active',
  discount_type TEXT NOT NULL DEFAULT 'none',
  discount_value REAL NOT NULL DEFAULT 0,
  discount_tiers_json TEXT,
  created_at TEXT NOT NULL
)");
$pdo->exec("CREATE TABLE IF NOT EXISTS package_items (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  package_id INTEGER NOT NULL,
  service_id INTEGER NOT NULL,
  quantity INTEGER NOT NULL DEFAULT 1,
  UNIQUE(package_id, service_id)
)");

function api_error(string $msg, int $code=400){ http_response_code($code); echo json_encode(['error'=>$msg]); exit; }

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
if ($method === 'GET') {
  $rows = $pdo->query("SELECT * FROM packages ORDER BY created_at DESC")->fetchAll();
  foreach ($rows as &$r) {
    $items = $pdo->prepare("SELECT s.id, s.service_name, (s.cac_fee+s.service_fee) as price, pi.quantity FROM package_items pi JOIN services s ON s.id=pi.service_id WHERE pi.package_id=?");
    $items->execute([$r['id']]); $r['items'] = $items->fetchAll();
  }
  echo json_encode(['packages'=>$rows]); exit;
}

$payload = json_decode(file_get_contents('php://input') ?: '[]', true);
if (!is_array($payload)) $payload = [];

if ($method === 'POST') {
  $name = sanitize_str($payload['name'] ?? '');
  $description = sanitize_str($payload['description'] ?? '');
  $dtype = $payload['discount_type'] ?? 'none';
  $dval = (float)($payload['discount_value'] ?? 0);
  $tiers = isset($payload['discount_tiers_json']) ? json_encode($payload['discount_tiers_json']) : null;
  $now = date('c');
  $stmt = $pdo->prepare("INSERT INTO packages (name,description,status,discount_type,discount_value,discount_tiers_json,created_at) VALUES (?,?,?,?,?,?,?)");
  $stmt->execute([$name,$description,'active',$dtype,$dval,$tiers,$now]);
  echo json_encode(['ok'=>true,'id'=>$pdo->lastInsertId()]); exit;
}

if ($method === 'PUT' || ($method === 'POST' && ($payload['_method'] ?? '')==='PUT')) {
  $id = (int)($payload['id'] ?? 0); if ($id<=0) api_error('id required');
  $name = sanitize_str($payload['name'] ?? '');
  $description = sanitize_str($payload['description'] ?? '');
  $dtype = $payload['discount_type'] ?? 'none';
  $dval = (float)($payload['discount_value'] ?? 0);
  $tiers = isset($payload['discount_tiers_json']) ? json_encode($payload['discount_tiers_json']) : null;
  $pdo->prepare("UPDATE packages SET name=?,description=?,discount_type=?,discount_value=?,discount_tiers_json=? WHERE id=?")->execute([$name,$description,$dtype,$dval,$tiers,$id]);
  echo json_encode(['ok'=>true]); exit;
}

if ($method === 'DELETE') {
  parse_str($_SERVER['QUERY_STRING'] ?? '', $q);
  $id = (int)($q['id'] ?? 0); if ($id<=0) api_error('id required');
  $pdo->prepare("DELETE FROM packages WHERE id=?")->execute([$id]);
  echo json_encode(['ok'=>true]); exit;
}

api_error('Unsupported method',405);
