<?php
require_once '../config/cors.php';
require_once '../config/database.php';
require_once '../utils/helpers.php';

// Authenticate user
$token = getAuthToken();
$user = getUserFromToken($token);

if (!$user || $user['role'] !== 'admin') {
    errorResponse('Unauthorized: Admin access required', 403);
}

$method = $_SERVER['REQUEST_METHOD'];
$data = json_decode(file_get_contents('php://input'), true);

try {
    if ($method === 'POST') {
        $action = $data['action'] ?? 'list';

        if ($action === 'create' || $action === 'update') {
            $name = $data['name'];
            $price = $data['price'];
            $description = $data['description'];
            $features = json_encode($data['features'] ?? []);
            $not_included = json_encode($data['notIncluded'] ?? []);
            $is_popular = $data['popular'] ? 1 : 0;
            $color = $data['color'];
            $button_text = $data['buttonText'];
            $order_index = $data['order_index'] ?? 0;

            if ($action === 'create') {
                $stmt = $pdo->prepare("INSERT INTO pricing_plans (name, price, description, features_json, not_included_json, is_popular, color_gradient, button_text, order_index) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$name, $price, $description, $features, $not_included, $is_popular, $color, $button_text, $order_index]);
                jsonResponse(['success' => true, 'message' => 'Plan created']);
            } else {
                $id = $data['id'];
                $stmt = $pdo->prepare("UPDATE pricing_plans SET name=?, price=?, description=?, features_json=?, not_included_json=?, is_popular=?, color_gradient=?, button_text=?, order_index=? WHERE id=?");
                $stmt->execute([$name, $price, $description, $features, $not_included, $is_popular, $color, $button_text, $order_index, $id]);
                jsonResponse(['success' => true, 'message' => 'Plan updated']);
            }
        } elseif ($action === 'delete') {
            $id = $data['id'];
            $stmt = $pdo->prepare("DELETE FROM pricing_plans WHERE id=?");
            $stmt->execute([$id]);
            jsonResponse(['success' => true, 'message' => 'Plan deleted']);
        }
    } else {
        // GET (same as public, but wrapped)
        $stmt = $pdo->query("SELECT * FROM pricing_plans ORDER BY order_index ASC");
        $plans = $stmt->fetchAll();
        foreach ($plans as &$plan) {
            $plan['features'] = json_decode($plan['features_json'] ?? '[]') ?: [];
            $plan['notIncluded'] = json_decode($plan['not_included_json'] ?? '[]') ?: [];
            $plan['popular'] = (bool)$plan['is_popular'];
            $plan['buttonText'] = $plan['button_text'];
            $plan['color'] = $plan['color_gradient'];
        }
        jsonResponse(['plans' => $plans]);
    }
} catch (PDOException $e) {
    errorResponse('Database error: ' . $e->getMessage(), 500);
}
