<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/auth_admin.php';
require_once __DIR__ . '/../../includes/audit.php';

apply_cors();
$admin = require_admin();
$pdo = getDbConnection();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

// GET    /plans.php               -> list all
// POST   /plans.php               -> create
// PUT    /plans.php?id=5          -> update
// PATCH  /plans.php?id=5&action=status -> enable/disable
// DELETE /plans.php?id=5          -> delete

if ($method === 'GET') {
    $stmt = $pdo->query('SELECT * FROM subscriptions ORDER BY display_order ASC, price ASC');
    send_success(['plans' => $stmt->fetchAll()]);
}

if ($method === 'POST') {
    $input = get_json_input();
    require_fields($input, ['plan_name', 'price', 'validity_days']);

    $maxOrder = (int) $pdo->query('SELECT COALESCE(MAX(display_order),0) FROM subscriptions')->fetchColumn();

    $stmt = $pdo->prepare(
        'INSERT INTO subscriptions (plan_name, price, validity_days, description, is_active, display_order)
         VALUES (:name, :price, :validity, :description, :active, :order)'
    );
    $stmt->execute([
        ':name'        => clean_str($input['plan_name']),
        ':price'       => (float) $input['price'],
        ':validity'    => (int) $input['validity_days'],
        ':description' => clean_str($input['description'] ?? ''),
        ':active'      => isset($input['is_active']) ? (int) (bool) $input['is_active'] : 1,
        ':order'       => $maxOrder + 1,
    ]);

    $newId = (int) $pdo->lastInsertId();
    log_admin_action($admin['email'], 'CREATE_PLAN', 'plan_id:' . $newId, clean_str($input['plan_name']));
    send_success(['plan_id' => $newId], 'Plan created.', 201);
}

if ($method === 'PUT' && isset($_GET['id'])) {
    $id = (int) $_GET['id'];
    $input = get_json_input();

    $fields = [];
    $params = [':id' => $id];
    if (isset($input['plan_name'])) { $fields[] = 'plan_name = :name'; $params[':name'] = clean_str($input['plan_name']); }
    if (isset($input['price'])) { $fields[] = 'price = :price'; $params[':price'] = (float) $input['price']; }
    if (isset($input['validity_days'])) { $fields[] = 'validity_days = :validity'; $params[':validity'] = (int) $input['validity_days']; }
    if (isset($input['description'])) { $fields[] = 'description = :description'; $params[':description'] = clean_str($input['description']); }
    if (empty($fields)) send_error('No fields to update.', 422);

    $stmt = $pdo->prepare('UPDATE subscriptions SET ' . implode(', ', $fields) . ' WHERE id = :id');
    $stmt->execute($params);

    log_admin_action($admin['email'], 'UPDATE_PLAN', 'plan_id:' . $id, '');
    send_success(null, 'Plan updated.');
}

if ($method === 'PATCH' && isset($_GET['id']) && $action === 'status') {
    $id = (int) $_GET['id'];
    $input = get_json_input();
    require_fields($input, ['is_active']);

    $stmt = $pdo->prepare('UPDATE subscriptions SET is_active = :active WHERE id = :id');
    $stmt->execute([':active' => $input['is_active'] ? 1 : 0, ':id' => $id]);

    log_admin_action($admin['email'], 'TOGGLE_PLAN', 'plan_id:' . $id, '');
    send_success(null, 'Plan status updated.');
}

if ($method === 'DELETE' && isset($_GET['id'])) {
    $stmt = $pdo->prepare('DELETE FROM subscriptions WHERE id = :id');
    $stmt->execute([':id' => (int) $_GET['id']]);

    log_admin_action($admin['email'], 'DELETE_PLAN', 'plan_id:' . $_GET['id'], '');
    send_success(null, 'Plan deleted.');
}

send_error('Invalid request.', 400);
