<?php
// GET ?action=cable_plans&api_key=KEY&provider=GOTV
// Returns cable TV plans

$provider = strtoupper(trim($_GET['provider'] ?? ''));
if (empty($provider)) {
    api_response(['status' => 'error', 'message' => 'Missing provider. Use: GOTV, DSTV, STARTIMES'], 400);
}

$api_markup = $GLOBALS['api_markup'];

try {
    $stmt = $pdo->prepare(
        "SELECT id, provider, plan_name, plan_code, price, validity
           FROM vtu_cable_plans
          WHERE UPPER(provider) = :prov AND status = 1
          ORDER BY price ASC"
    );
    $stmt->execute([':prov' => $provider]);
    $plans = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    api_response(['status' => 'error', 'message' => 'Database error.'], 500);
}

$result = [];
foreach ($plans as $p) {
    $price = (float)$p['price'];
    if ($api_markup > 0) $price = round($price * (1 + $api_markup / 100), 2);
    $result[] = [
        'plan_id'   => (int)$p['id'],
        'provider'  => $p['provider'],
        'name'      => $p['plan_name'],
        'price'     => number_format($price, 2, '.', ''),
        'validity'  => $p['validity'] ?? '',
    ];
}

api_response([
    'status' => 'success',
    'count'  => count($result),
    'plans'  => $result,
]);
