<?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 request 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);

switch ($action) {
    case 'toggle_active':
        $is_active = (int) ($_POST['is_active'] ?? 0);
        $db->update('subscription_plans', ['is_active' => $is_active, 'updated_at' => date('Y-m-d H:i:s')], 'id = ?', [$planId]);
        jsonResponse(true, 'Plan status updated.');
        break;

    case 'delete':
        $restaurantCount = $db->count('restaurants', 'plan_id = ?', [$planId]);
        if ($restaurantCount > 0) {
            jsonResponse(false, 'Cannot delete plan with assigned restaurants.');
        }
        $db->delete('subscription_plans', 'id = ?', [$planId]);
        jsonResponse(true, 'Plan deleted successfully.');
        break;

    case 'save':
    default:
        $name = trim($_POST['name'] ?? '');
        if (empty($name)) {
            jsonResponse(false, 'Plan name is required.');
        }

        $slug = trim($_POST['slug'] ?? slugify($name));
        $description = trim($_POST['description'] ?? '');
        $monthlyPrice = (float) ($_POST['monthly_price'] ?? 0);
        $annualPrice = (float) ($_POST['annual_price'] ?? 0);
        $maxMenuItems = (int) ($_POST['max_menu_items'] ?? 50);
        $maxStaff = (int) ($_POST['max_staff'] ?? 3);
        $maxTables = (int) ($_POST['max_tables'] ?? 10);
        $maxBranches = (int) ($_POST['max_branches'] ?? 1);
        $featuresRaw = $_POST['features'] ?? '[]';
        $isRecommended = isset($_POST['is_recommended']) ? 1 : 0;
        $isActive = isset($_POST['is_active']) ? 1 : 0;
        $sortOrder = (int) ($_POST['sort_order'] ?? 0);

        $features = $featuresRaw;
        if (is_string($featuresRaw)) {
            $decoded = json_decode($featuresRaw, true);
            $features = is_array($decoded) ? json_encode($decoded) : json_encode([$featuresRaw]);
        } else {
            $features = json_encode($featuresRaw);
        }

        $data = [
            'name' => $name,
            'slug' => $slug,
            'description' => $description,
            'monthly_price' => $monthlyPrice,
            'annual_price' => $annualPrice,
            'max_menu_items' => $maxMenuItems,
            'max_staff' => $maxStaff,
            'max_tables' => $maxTables,
            'max_branches' => $maxBranches,
            'features' => $features,
            'is_recommended' => $isRecommended,
            'is_active' => $isActive,
            'sort_order' => $sortOrder,
            'updated_at' => date('Y-m-d H:i:s'),
        ];

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