<?php
session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';
header('Content-Type: application/json; charset=utf-8');

$auth = new Auth();
if (!$auth->check() || !$auth->isSuperAdmin()) { jsonResponse(false, 'Unauthorized', [], 401); }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { jsonResponse(false, 'Invalid method.'); }

$csrf = new CSRF();
if (!$csrf->verify($_POST['csrf_token'] ?? '')) { jsonResponse(false, 'Invalid CSRF token.'); }

$db = Database::getInstance();
$action = $_POST['action'] ?? 'save';
$planId = (int) ($_POST['plan_id'] ?? 0);

if ($action === 'delete') {
    $db->delete('pricing_plans', 'id = ?', [$planId]);
    jsonResponse(true, 'Pricing plan deleted.');
}

$planName = trim($_POST['plan_name'] ?? '');
if (empty($planName)) { jsonResponse(false, 'Plan name is required.'); }

$monthlyPrice = (float) ($_POST['monthly_price'] ?? 0);
$annualPrice = (float) ($_POST['annual_price'] ?? 0);
$description = trim($_POST['description'] ?? '');
$featuresRaw = $_POST['features'] ?? '[]';
$features = is_string($featuresRaw) ? $featuresRaw : json_encode($featuresRaw);
$decoded = json_decode($features, true);
$featuresJson = is_array($decoded) ? json_encode($decoded) : json_encode([$featuresRaw]);
$isRecommended = isset($_POST['is_recommended']) ? 1 : 0;
$isActive = isset($_POST['is_active']) ? 1 : 0;
$sortOrder = (int) ($_POST['sort_order'] ?? 0);

$data = [
    'plan_name' => $planName,
    'monthly_price' => $monthlyPrice,
    'annual_price' => $annualPrice,
    'description' => $description,
    'features' => $featuresJson,
    'is_recommended' => $isRecommended,
    'is_active' => $isActive,
    'sort_order' => $sortOrder,
    'updated_at' => date('Y-m-d H:i:s'),
];

if ($planId > 0) {
    $db->update('pricing_plans', $data, 'id = ?', [$planId]);
    jsonResponse(true, 'Pricing plan updated.');
} else {
    $data['created_at'] = date('Y-m-d H:i:s');
    $db->insert('pricing_plans', $data);
    jsonResponse(true, 'Pricing plan created.');
}
