<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| ASOVERIFY DATA PLAN MANAGER
|--------------------------------------------------------------------------
| Save as: /admin/data_plan_manager.php
| DB:      db.php (MySQLi $conn)
| Config:  ../data/vtu_admin_config.php (api_key, pin, base_url)
| Table:   plan_prices
| PHP 7.1+
|--------------------------------------------------------------------------
*/

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
ini_set('log_errors', '1');
ini_set('display_errors', '0');

/* Set to false once the page works. While true, errors are shown on screen. */
const DPM_DEBUG = true;

function dpm_show_error(string $msg, string $file, int $line): void
{
    error_log('ASOVERIFY plan manager: ' . $msg . ' @ ' . $file . ':' . $line);
    if (!headers_sent()) {
        http_response_code(500);
    }
    echo '<pre style="padding:20px;font:14px monospace;white-space:pre-wrap">Plan manager error';
    if (DPM_DEBUG) {
        echo ":\n" . htmlspecialchars($msg, ENT_QUOTES, 'UTF-8')
            . "\nFile: " . htmlspecialchars(basename($file), ENT_QUOTES, 'UTF-8')
            . "\nLine: " . $line;
    } else {
        echo '. Check the server error log.';
    }
    echo '</pre>';
}

set_exception_handler(function (Throwable $e) {
    dpm_show_error($e->getMessage(), $e->getFile(), (int)$e->getLine());
});

register_shutdown_function(function () {
    $err = error_get_last();
    if ($err && in_array($err['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR], true)) {
        dpm_show_error($err['message'], $err['file'], (int)$err['line']);
    }
});

function dpm_h($v): string
{
    return htmlspecialchars((string)$v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function dpm_money($v): string
{
    return '₦' . number_format((float)$v, 2);
}

function dpm_redirect(): void
{
    header('Location: data_plan_manager.php', true, 303);
    exit;
}

/* -------------------- DATABASE -------------------- */

$dbFile = null;
foreach ([__DIR__ . '/db.php', dirname(__DIR__) . '/db.php', dirname(__DIR__) . '/includes/db.php'] as $candidate) {
    if (is_file($candidate)) {
        $dbFile = $candidate;
        break;
    }
}

if ($dbFile === null) {
    exit('db.php was not found. Place it in /admin/ or in the site root.');
}

require_once $dbFile;

/* Accept the common connection variable names. */
if (!isset($conn) || !($conn instanceof mysqli)) {
    foreach (['mysqli', 'db', 'link', 'connection'] as $name) {
        if (isset($$name) && $$name instanceof mysqli) {
            $conn = $$name;
            break;
        }
    }
}

if (!isset($conn) || !($conn instanceof mysqli)) {
    exit('db.php did not provide a MySQLi connection ($conn).');
}

$conn->set_charset('utf8mb4');

/* -------------------- ADMIN AUTHENTICATION -------------------- */

$loginUrl = is_file(__DIR__ . '/admin_login.php') ? '/admin/admin_login.php'
    : (is_file(__DIR__ . '/login.php') ? '/admin/login.php' : '/admin/admin_login.php');

if (empty($_SESSION['admin'])) {
    header('Location: ' . $loginUrl);
    exit;
}

$adminSession = $_SESSION['admin'];
$adminId = isset($_SESSION['admin_id']) ? (int)$_SESSION['admin_id'] : 0;

if ($adminId > 0) {
    $stmt = $conn->prepare(
        'SELECT id, name, email, admin_rank FROM admin WHERE id = ? LIMIT 1'
    );
    $stmt->bind_param('i', $adminId);
} else {
    $identity = is_scalar($adminSession) ? trim((string)$adminSession) : '';

    if ($identity === '') {
        header('Location: ' . $loginUrl);
        exit;
    }

    $stmt = $conn->prepare(
        'SELECT id, name, email, admin_rank
         FROM admin
         WHERE email = ? OR name = ? OR CAST(id AS CHAR) = ?
         LIMIT 1'
    );
    $stmt->bind_param('sss', $identity, $identity, $identity);
}

$stmt->execute();
$admin = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$admin) {
    http_response_code(403);
    exit('Access denied. Please sign in through the ASOVERIFY admin login.');
}

$rank = strtoupper(trim((string)$admin['admin_rank']));

if (!in_array($rank, ['MD', 'STAFF', 'DIRECTOR'], true)) {
    http_response_code(403);
    exit('Your admin rank does not permit access to this page.');
}

/*
 * If your installation uses admin_page_guard.php for service assignments,
 * include it here and assign this page its service key.
 */

/* -------------------- CSRF -------------------- */

if (empty($_SESSION['dpm_csrf'])) {
    $_SESSION['dpm_csrf'] = bin2hex(random_bytes(32));
}
$csrf = (string)$_SESSION['dpm_csrf'];

/* -------------------- SCHEMA CHECK (read-only safe) -------------------- */

function dpm_columns(mysqli $conn): array
{
    $cols = [];
    $res = $conn->query('SHOW COLUMNS FROM plan_prices');
    while ($c = $res->fetch_assoc()) {
        $cols[$c['Field']] = true;
    }
    return $cols;
}

$cols = dpm_columns($conn);

$needed = [
    'markup_type'  => "ADD COLUMN markup_type VARCHAR(20) NOT NULL DEFAULT 'fixed'",
    'markup_value' => "ADD COLUMN markup_value DECIMAL(12,2) NOT NULL DEFAULT 0",
];

foreach ($needed as $col => $ddl) {
    if (!isset($cols[$col])) {
        try {
            $conn->query("ALTER TABLE plan_prices $ddl");
        } catch (Throwable $e) {
            error_log('ASOVERIFY could not add column ' . $col . ': ' . $e->getMessage());
        }
    }
}

$cols = dpm_columns($conn);
$missing = [];
foreach (['id', 'category', 'network', 'plan_id', 'plan_name', 'cost_price',
          'selling_price', 'status', 'markup_type', 'markup_value'] as $col) {
    if (!isset($cols[$col])) {
        $missing[] = $col;
    }
}

if ($missing) {
    http_response_code(500);
    exit('plan_prices is missing columns: ' . dpm_h(implode(', ', $missing))
        . '. Add them in phpMyAdmin, then reload.');
}

/* Make sure cost_price is never NULL (existing rows are NULL). */
try {
    $conn->query('UPDATE plan_prices SET cost_price = 0 WHERE cost_price IS NULL');
} catch (Throwable $e) {
    error_log('ASOVERIFY cost_price cleanup: ' . $e->getMessage());
}

/* -------------------- API CONFIG -------------------- */

$apiConfig = [];
$configDiag = '';
$configFile = null;

$configCandidates = [dirname(__DIR__) . '/data/vtu_admin_config.php', __DIR__ . '/data/vtu_admin_config.php'];
if (!empty($_SERVER['DOCUMENT_ROOT'])) {
    $configCandidates[] = rtrim((string)$_SERVER['DOCUMENT_ROOT'], '/') . '/data/vtu_admin_config.php';
    $configCandidates[] = dirname(rtrim((string)$_SERVER['DOCUMENT_ROOT'], '/')) . '/data/vtu_admin_config.php';
}

foreach (array_unique($configCandidates) as $candidate) {
    if (is_file($candidate)) {
        $configFile = $candidate;
        break;
    }
}

if ($configFile === null) {
    $configDiag = 'Config file not found. Looked in: ' . implode(' | ', array_unique($configCandidates));
} else {
    /*
     * First read the settings as plain text, without executing the file.
     * This works even if the file has a PHP compile error (for example a
     * misplaced declare(strict_types=1)) and never runs unknown code.
     */
    $rawConfig = (string)@file_get_contents($configFile);
    $textParsed = [];

    if (preg_match_all(
        '/[\'"]([A-Za-z0-9_]+)[\'"]\s*(?:=>|,)\s*[\'"]([^\'"\r\n]*)[\'"]/',
        $rawConfig,
        $m,
        PREG_SET_ORDER
    )) {
        foreach ($m as $hit) {
            $textParsed[strtolower($hit[1])] = $hit[2];
        }
    }

    $hasAll = false;
    foreach (['api_key', 'apikey', 'token', 'key'] as $k) {
        if (!empty($textParsed[$k])) { $hasAll = true; break; }
    }
    $hasAll = $hasAll && !empty($textParsed['pin']) && (!empty($textParsed['base_url']) || !empty($textParsed['url']));

    if ($hasAll) {
        $apiConfig = $textParsed;
        $configDiag = 'Settings were read from the file text.';
    } else try {
        $loaded = (function ($file) {
            $returned = require $file;
            $vars = get_defined_vars();
            unset($vars['file'], $vars['returned']);
            return [$returned, $vars];
        })($configFile);

        $returned = $loaded[0];
        $vars = $loaded[1];

        if (is_array($returned)) {
            $apiConfig = $returned;
        } else {
            /* No return array: look for an array variable the file defined. */
            foreach ($vars as $vName => $vValue) {
                if (is_array($vValue) && $vValue) {
                    $apiConfig = $vValue;
                    break;
                }
            }
            if (!$apiConfig) {
                /* Fall back to user constants that look like API settings. */
                $consts = get_defined_constants(true);
                $userConsts = isset($consts['user']) ? $consts['user'] : [];
                foreach ($userConsts as $cName => $cValue) {
                    $lower = strtolower((string)$cName);
                    if (is_scalar($cValue) && (strpos($lower, 'sabuss') !== false
                        || strpos($lower, 'vtu') !== false || strpos($lower, 'api') !== false)) {
                        $apiConfig[preg_replace('/^(sabuss_|vtu_|api_)/', '', $lower) ?: $lower] = $cValue;
                        $apiConfig[$lower] = $cValue;
                    }
                }
            }
            $configDiag = 'File loaded but did not return an array (returned type: '
                . gettype($returned) . '). Variables defined: '
                . ($vars ? implode(', ', array_keys($vars)) : 'none') . '.';
        }
    } catch (Throwable $e) {
        $configDiag = 'Config file error: ' . $e->getMessage() . ' (line ' . $e->getLine() . ').';
    }
}

function dpm_api_request(string $category): array
{
    global $apiConfig;

    $aliases = [
        'api_key'  => ['api_key', 'apikey', 'key', 'token', 'api_token', 'secret_key'],
        'pin'      => ['pin', 'transaction_pin', 'api_pin', 'txn_pin'],
        'base_url' => ['base_url', 'baseurl', 'url', 'api_url', 'endpoint'],
    ];

    $flat = array_change_key_case($apiConfig, CASE_LOWER);
    foreach (['sabuss', 'vtu', 'api', 'provider'] as $wrap) {
        if (isset($flat[$wrap]) && is_array($flat[$wrap])) {
            $flat = array_merge($flat, array_change_key_case($flat[$wrap], CASE_LOWER));
        }
    }

    $resolved = [];
    $missingKeys = [];
    foreach ($aliases as $canonical => $names) {
        foreach ($names as $name) {
            if (isset($flat[$name]) && is_scalar($flat[$name]) && trim((string)$flat[$name]) !== '') {
                $resolved[$canonical] = trim((string)$flat[$name]);
                break;
            }
        }
        if (!isset($resolved[$canonical])) {
            $missingKeys[] = $canonical;
        }
    }

    if ($missingKeys) {
        global $configDiag, $configFile;
        $found = $apiConfig ? implode(', ', array_keys($apiConfig)) : 'none';
        throw new RuntimeException(
            'API config incomplete. Missing: ' . implode(', ', $missingKeys)
            . '. Keys found: ' . $found . '. File used: ' . ($configFile ?: 'none')
            . '. ' . $configDiag
        );
    }

    $apiConfig = $resolved; // normalized

    if (!function_exists('curl_init')) {
        throw new RuntimeException('PHP cURL is not enabled.');
    }

    $base = rtrim(trim($apiConfig['base_url']), '/');

    if (strtolower((string)parse_url($base, PHP_URL_SCHEME)) !== 'https') {
        throw new RuntimeException('The provider API must use HTTPS.');
    }

    $url = $base . '/plans/' . rawurlencode($apiConfig['api_key']);

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query([
            'pin' => $apiConfig['pin'],
            'category' => $category
        ]),
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/x-www-form-urlencoded',
            'Accept: application/json'
        ],
        CURLOPT_CONNECTTIMEOUT => 15,
        CURLOPT_TIMEOUT => 45,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_FOLLOWLOCATION => false
    ]);

    $body = curl_exec($ch);
    $error = curl_error($ch);
    $http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($body === false) {
        throw new RuntimeException('Provider connection failed: ' . $error);
    }

    $json = json_decode((string)$body, true);

    if (!is_array($json)) {
        throw new RuntimeException('Provider returned invalid JSON.');
    }

    if ($http < 200 || $http >= 300) {
        throw new RuntimeException('Provider HTTP error: ' . $http);
    }

    if (isset($json['code']) && is_numeric($json['code']) && (int)$json['code'] !== 200) {
        throw new RuntimeException('Provider rejected the plan request. Code: ' . $json['code']);
    }

    if (isset($json['success']) && $json['success'] === false) {
        throw new RuntimeException('Provider reported an unsuccessful request.');
    }

    return $json;
}

/* Finds the plan list in common response wrappers; never guesses blindly. */
function dpm_extract_plans(array $json): array
{
    $candidates = [
        isset($json['data']) ? $json['data'] : null,
        isset($json['plans']) ? $json['plans'] : null,
        isset($json['results']) ? $json['results'] : null,
        isset($json['data']['plans']) ? $json['data']['plans'] : null,
        isset($json['data']['results']) ? $json['data']['results'] : null
    ];

    foreach ($candidates as $candidate) {
        if (is_array($candidate) && isset($candidate['plans'])
            && is_array($candidate['plans'])) {
            $candidate = $candidate['plans'];
        }

        if (!is_array($candidate) || !$candidate) {
            continue;
        }

        $first = reset($candidate);

        if (is_array($first)) {
            return array_values($candidate);
        }
    }

    if (isset($json[0]) && is_array($json[0])) {
        return $json;
    }

    throw new RuntimeException(
        'Could not identify the plan list in the API response. '
        . 'No plans were changed. Inspect the provider response format.'
    );
}

function dpm_first_value(array $row, array $keys)
{
    foreach ($keys as $key) {
        if (isset($row[$key]) && is_scalar($row[$key]) && trim((string)$row[$key]) !== '') {
            return $row[$key];
        }
    }
    return null;
}

function dpm_network(string $network): string
{
    $network = strtoupper(trim($network));

    $aliases = [
        'MTN NIGERIA' => 'MTN',
        'AIRTEL NIGERIA' => 'AIRTEL',
        'GLO NIGERIA' => 'GLO',
        '9MOBILE NIGERIA' => '9MOBILE',
        'ETISALAT' => '9MOBILE'
    ];

    return isset($aliases[$network]) ? $aliases[$network] : $network;
}

function dpm_calculate_price(float $cost, string $type, float $value): float
{
    if ($cost <= 0) {
        return 0.00;
    }

    if ($type === 'percent') {
        return round($cost + ($cost * $value / 100), 2);
    }

    return round($cost + $value, 2);
}

/* -------------------- API SYNCHRONIZATION -------------------- */

function dpm_sync(string $category): array
{
    global $conn;

    $json = dpm_api_request($category);
    $plans = dpm_extract_plans($json);

    $added = 0;
    $updated = 0;
    $skipped = 0;

    foreach ($plans as $item) {
        if (!is_array($item)) {
            $skipped++;
            continue;
        }

        $pid = dpm_first_value($item, ['plan_id', 'id', 'planId', 'product_id', 'productId']);
        $net = dpm_first_value($item, ['network', 'network_name', 'service', 'operator']);
        $nm  = dpm_first_value($item, ['plan_name', 'name', 'plan', 'title', 'description', 'product_name']);
        $cv  = dpm_first_value($item, ['cost_price', 'provider_price', 'provider_cost', 'selling_cost', 'price']);

        if ($pid === null || !is_numeric($pid) || (int)$pid <= 0 || $net === null) {
            $skipped++;
            continue;
        }

        $providerId = (int)$pid;
        $network = dpm_network((string)$net);
        $name = trim((string)($nm !== null ? $nm : ('Plan #' . $providerId)));
        $cost = ($cv !== null && is_numeric($cv)) ? round((float)$cv, 2) : 0.00;

        $stmt = $conn->prepare(
            'SELECT id, cost_price, markup_type, markup_value, selling_price
             FROM plan_prices
             WHERE LOWER(category)=LOWER(?)
               AND LOWER(network)=LOWER(?)
               AND plan_id=?
             ORDER BY id ASC LIMIT 1'
        );
        $stmt->bind_param('ssi', $category, $network, $providerId);
        $stmt->execute();
        $old = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if ($old) {
            $localId = (int)$old['id'];
            $effectiveCost = $cost > 0 ? $cost : (float)$old['cost_price'];
            $markupValue = (float)$old['markup_value'];
            $selling = (float)$old['selling_price'];

            /* Re-price only when a markup was deliberately saved. */
            if ($markupValue > 0 && $effectiveCost > 0) {
                $selling = dpm_calculate_price(
                    $effectiveCost,
                    (string)$old['markup_type'],
                    $markupValue
                );
            }

            $stmt = $conn->prepare(
                'UPDATE plan_prices SET plan_name=?, cost_price=?, selling_price=? WHERE id=?'
            );
            $stmt->bind_param('sddi', $name, $effectiveCost, $selling, $localId);
            $stmt->execute();
            $stmt->close();
            $updated++;
        } else {
            /* New plans start inactive so they cannot be sold at ₦0. */
            $status = 'inactive';
            $markupType = 'fixed';
            $markupValue = 0.00;
            $selling = 0.00;

            $stmt = $conn->prepare(
                'INSERT INTO plan_prices
                 (category, network, plan_id, plan_name, selling_price,
                  status, cost_price, markup_type, markup_value)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'
            );
            // s s i s d s d s d
            $stmt->bind_param(
                'ssisdsdsd',
                $category, $network, $providerId, $name, $selling,
                $status, $cost, $markupType, $markupValue
            );
            $stmt->execute();
            $stmt->close();
            $added++;
        }
    }

    return [
        'total' => count($plans),
        'added' => $added,
        'updated' => $updated,
        'skipped' => $skipped
    ];
}

/* -------------------- FLASH MESSAGES -------------------- */

function dpm_flash(string $message, string $type = 'success'): void
{
    $_SESSION['dpm_message'] = $message;
    $_SESSION['dpm_message_type'] = $type;
}

$message = (string)($_SESSION['dpm_message'] ?? '');
$messageType = (string)($_SESSION['dpm_message_type'] ?? 'success');
unset($_SESSION['dpm_message'], $_SESSION['dpm_message_type']);

/* -------------------- FORM ACTIONS -------------------- */

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        $postedToken = (string)($_POST['csrf_token'] ?? '');

        if ($postedToken === '' || !hash_equals($csrf, $postedToken)) {
            throw new RuntimeException('Security token expired. Refresh and retry.');
        }

        $action = (string)($_POST['action'] ?? '');

        if ($action === 'save_plan') {
            $id = (int)($_POST['id'] ?? 0);
            $category = strtolower(trim((string)($_POST['category'] ?? '')));
            $network = dpm_network((string)($_POST['network'] ?? ''));
            $planId = (int)($_POST['plan_id'] ?? 0);
            $name = trim((string)($_POST['plan_name'] ?? ''));
            $cost = round((float)($_POST['cost_price'] ?? 0), 2);
            $markupType = (string)($_POST['markup_type'] ?? 'fixed');
            $markupValue = round((float)($_POST['markup_value'] ?? 0), 2);
            $selling = round((float)($_POST['selling_price'] ?? 0), 2);
            $status = (string)($_POST['status'] ?? 'inactive');

            if (!in_array($category, ['data', 'airtime'], true)
                || $network === '' || $planId <= 0 || $name === '') {
                throw new RuntimeException('Fill in all required plan fields.');
            }
            if (!in_array($markupType, ['fixed', 'percent'], true)) {
                throw new RuntimeException('Invalid markup type.');
            }
            if (!in_array($status, ['active', 'inactive'], true)) {
                throw new RuntimeException('Invalid status.');
            }
            if ($cost < 0 || $selling < 0 || $markupValue < 0) {
                throw new RuntimeException('Prices and markup cannot be negative.');
            }

            if (isset($_POST['auto_price']) && $_POST['auto_price'] === '1') {
                $selling = dpm_calculate_price($cost, $markupType, $markupValue);
            }

            if ($status === 'active' && $selling <= 0) {
                throw new RuntimeException(
                    'A plan cannot be active with a ₦0 selling price. Set a price first.'
                );
            }

            if ($id > 0) {
                $stmt = $conn->prepare(
                    'UPDATE plan_prices
                     SET category=?, network=?, plan_id=?, plan_name=?,
                         cost_price=?, markup_type=?, markup_value=?,
                         selling_price=?, status=?
                     WHERE id=?'
                );
                // s s i s d s d d s i
                $stmt->bind_param(
                    'ssisdsddsi',
                    $category, $network, $planId, $name,
                    $cost, $markupType, $markupValue, $selling, $status, $id
                );
                $stmt->execute();
                $stmt->close();
            } else {
                $stmt = $conn->prepare(
                    'SELECT id FROM plan_prices
                     WHERE LOWER(category)=LOWER(?)
                       AND LOWER(network)=LOWER(?) AND plan_id=?
                     LIMIT 1'
                );
                $stmt->bind_param('ssi', $category, $network, $planId);
                $stmt->execute();
                $duplicate = $stmt->get_result()->fetch_assoc();
                $stmt->close();

                if ($duplicate) {
                    throw new RuntimeException(
                        'This provider plan already exists. Edit the existing row instead.'
                    );
                }

                $stmt = $conn->prepare(
                    'INSERT INTO plan_prices
                     (category, network, plan_id, plan_name, cost_price,
                      markup_type, markup_value, selling_price, status)
                     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'
                );
                // s s i s d s d d s
                $stmt->bind_param(
                    'ssisdsdds',
                    $category, $network, $planId, $name,
                    $cost, $markupType, $markupValue, $selling, $status
                );
                $stmt->execute();
                $stmt->close();
            }

            dpm_flash('Plan saved successfully.');

        } elseif ($action === 'generate_prices') {
            $type = (string)($_POST['bulk_type'] ?? 'fixed');
            $value = round((float)($_POST['bulk_value'] ?? 0), 2);
            $category = strtolower(trim((string)($_POST['bulk_category'] ?? 'all')));

            if (!in_array($type, ['fixed', 'percent'], true)
                || $value < 0
                || !in_array($category, ['all', 'data', 'airtime'], true)) {
                throw new RuntimeException('Invalid bulk pricing settings.');
            }

            if ($category === 'all') {
                $sel = $conn->prepare('SELECT id, cost_price FROM plan_prices WHERE cost_price > 0');
            } else {
                $sel = $conn->prepare(
                    'SELECT id, cost_price FROM plan_prices
                     WHERE cost_price > 0 AND LOWER(category)=?'
                );
                $sel->bind_param('s', $category);
            }
            $sel->execute();
            $result = $sel->get_result();

            $upd = $conn->prepare(
                'UPDATE plan_prices SET markup_type=?, markup_value=?, selling_price=? WHERE id=?'
            );

            $count = 0;
            while ($row = $result->fetch_assoc()) {
                $rid = (int)$row['id'];
                $selling = dpm_calculate_price((float)$row['cost_price'], $type, $value);

                $upd->bind_param('sddi', $type, $value, $selling, $rid);
                $upd->execute();
                $count++;
            }

            $sel->close();
            $upd->close();

            dpm_flash(
                $count . ' plans repriced. Plans without a provider cost were left unchanged.'
            );

        } elseif ($action === 'toggle') {
            $id = (int)($_POST['id'] ?? 0);

            $stmt = $conn->prepare(
                'SELECT status, selling_price FROM plan_prices WHERE id=? LIMIT 1'
            );
            $stmt->bind_param('i', $id);
            $stmt->execute();
            $row = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            if (!$row) {
                throw new RuntimeException('Plan not found.');
            }

            $isActive = strtolower((string)$row['status']) === 'active';

            if (!$isActive && (float)$row['selling_price'] <= 0) {
                throw new RuntimeException(
                    'Cannot activate a plan with a ₦0 selling price. Set a price first.'
                );
            }

            $newStatus = $isActive ? 'inactive' : 'active';
            $stmt = $conn->prepare('UPDATE plan_prices SET status=? WHERE id=?');
            $stmt->bind_param('si', $newStatus, $id);
            $stmt->execute();
            $stmt->close();

            dpm_flash('Plan status updated.');

        } elseif ($action === 'sync') {
            $category = (string)($_POST['category'] ?? '');

            if (!in_array($category, ['data', 'airtime'], true)) {
                throw new RuntimeException('Choose data or airtime to synchronize.');
            }

            $r = dpm_sync($category);

            dpm_flash(
                'API sync complete: ' . $r['added'] . ' added, '
                . $r['updated'] . ' updated, ' . $r['skipped'] . ' skipped. '
                . 'Review costs and set your selling markup before activating plans.'
            );
        } else {
            throw new RuntimeException('Unknown admin action.');
        }
    } catch (Throwable $e) {
        error_log('ASOVERIFY plan manager: ' . $e->getMessage());
        dpm_flash($e->getMessage(), 'error');
    }

    dpm_redirect();
}

/* -------------------- FILTERS AND TABLE -------------------- */

$filterCategory = strtolower(trim((string)($_GET['category'] ?? 'all')));
$filterNetwork = trim((string)($_GET['network'] ?? ''));
$filterStatus = strtolower(trim((string)($_GET['status'] ?? 'all')));
$search = trim((string)($_GET['q'] ?? ''));

if (!in_array($filterCategory, ['all', 'data', 'airtime'], true)) {
    $filterCategory = 'all';
}
if (!in_array($filterStatus, ['all', 'active', 'inactive'], true)) {
    $filterStatus = 'all';
}

$sql = 'SELECT id, category, network, plan_id, plan_name,
               COALESCE(cost_price,0) AS cost_price,
               COALESCE(selling_price,0) AS selling_price,
               status, markup_type, markup_value
        FROM plan_prices WHERE 1=1';
$params = [];
$types = '';

if ($filterCategory !== 'all') {
    $sql .= ' AND LOWER(category)=?';
    $params[] = $filterCategory;
    $types .= 's';
}
if ($filterStatus !== 'all') {
    $sql .= ' AND LOWER(status)=?';
    $params[] = $filterStatus;
    $types .= 's';
}
if ($filterNetwork !== '') {
    $sql .= ' AND network=?';
    $params[] = $filterNetwork;
    $types .= 's';
}
if ($search !== '') {
    $sql .= ' AND (plan_name LIKE ? OR network LIKE ? OR CAST(plan_id AS CHAR) LIKE ?)';
    $like = '%' . $search . '%';
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $types .= 'sss';
}

$sql .= ' ORDER BY network, category, plan_name LIMIT 500';

$stmt = $conn->prepare($sql);
if ($params) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$plansResult = $stmt->get_result();
$plans = [];

while ($row = $plansResult->fetch_assoc()) {
    $plans[] = $row;
}
$stmt->close();

$stats = ['total' => 0, 'active' => 0, 'data' => 0, 'airtime' => 0];
$result = $conn->query(
    "SELECT COUNT(*) AS total,
            COALESCE(SUM(LOWER(status)='active'),0) AS active_count,
            COALESCE(SUM(LOWER(category)='data'),0) AS data_count,
            COALESCE(SUM(LOWER(category)='airtime'),0) AS airtime_count
     FROM plan_prices"
);
if ($row = $result->fetch_assoc()) {
    $stats['total'] = (int)$row['total'];
    $stats['active'] = (int)$row['active_count'];
    $stats['data'] = (int)$row['data_count'];
    $stats['airtime'] = (int)$row['airtime_count'];
}

$networks = [];
$result = $conn->query('SELECT DISTINCT network FROM plan_prices ORDER BY network');
while ($row = $result->fetch_assoc()) {
    $networks[] = (string)$row['network'];
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#00bfff">
<title>ASOVERIFY | Data Plan Manager</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
<style>
:root{--bg:#07182b;--panel:#102943;--panel2:#0b223a;--line:rgba(255,255,255,.09);--text:#eff7ff;--muted:#9eb4ca;--cyan:#00bfff;--green:#6ee7a8;--red:#fda4af}
*{box-sizing:border-box}
body{margin:0;padding:15px;background:radial-gradient(ellipse at top left,#0b3652,#07182b 60%);color:var(--text);font-family:Inter,Arial,sans-serif}
.wrap{max-width:1500px;margin:auto}
.top,.panel{background:rgba(16,41,67,.96);border:1px solid var(--line);border-radius:18px}
.top{padding:20px;display:flex;justify-content:space-between;align-items:center;gap:15px;flex-wrap:wrap;margin-bottom:17px}
.brand{font-weight:900;font-size:19px}.brand span{color:var(--cyan)}
.muted{color:var(--muted);font-size:12px;line-height:1.6}
.pill{padding:8px 12px;border-radius:30px;background:#0b223a;border:1px solid var(--line);font-size:11px}
h1{font-size:clamp(24px,4vw,34px);margin:0 0 8px}
h2{font-size:16px;margin:0 0 8px}
.hero{padding:22px;margin-bottom:17px}
.stats{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin-bottom:17px}
.stat{padding:17px;background:var(--panel);border:1px solid var(--line);border-radius:15px}
.stat small{display:block;color:var(--muted);font-size:11px;margin-bottom:9px}
.stat strong{font-size:25px}
.grid>*{min-width:0}
.grid{display:grid;grid-template-columns:minmax(280px,360px) minmax(0,1fr);gap:17px;align-items:start}
.panel{padding:19px;margin-bottom:17px}
label{display:block;color:#bdcddd;font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.05em;margin:12px 0 7px}
input,select{width:100%;min-height:43px;border:1px solid var(--line);border-radius:10px;padding:10px;background:var(--panel2);color:white;font:inherit;font-size:12px}
select option{background:var(--panel2)}
button,.btn{border:0;border-radius:10px;padding:12px 14px;background:linear-gradient(110deg,#effcff,#00bfff);color:#052039;font-weight:900;font-size:11px;cursor:pointer;text-decoration:none;display:inline-flex;align-items:center;justify-content:center;gap:7px}
button.secondary,.btn.secondary{background:#173b59;color:white;border:1px solid var(--line)}
button.small{padding:8px 10px;font-size:10px}
.full{width:100%;margin-top:13px}
.row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
.flash{padding:14px;border-radius:12px;margin-bottom:15px;background:#123b34;color:#b6f8d5;font-size:12px;line-height:1.6}
.flash.error{background:#48212a;color:#ffc4cb}
.filters{display:grid;grid-template-columns:repeat(4,minmax(100px,1fr));gap:9px;margin-bottom:13px}
.table-wrap{overflow:auto}
table{width:100%;border-collapse:collapse;min-width:1000px}
th,td{padding:12px 10px;text-align:left;border-bottom:1px solid var(--line);font-size:11px;vertical-align:middle}
th{font-size:9px;color:var(--muted);text-transform:uppercase;letter-spacing:.06em}
td strong{display:block;margin-bottom:5px}
.tag{display:inline-block;padding:5px 8px;border-radius:30px;background:#183b58;font-size:9px;font-weight:800}
.tag.active{background:#123d32;color:var(--green)}.tag.inactive{background:#47212a;color:var(--red)}
.price{font-weight:900;color:#8fe8ff;white-space:nowrap}
.actions{display:flex;gap:6px;flex-wrap:wrap}
.empty{text-align:center;padding:30px;color:var(--muted)}
small.note{display:block;color:var(--muted);font-size:10px;line-height:1.6;margin-top:10px}
@media(max-width:1000px){.grid{grid-template-columns:minmax(0,1fr)}.stats{grid-template-columns:repeat(2,minmax(0,1fr))}}
@media(max-width:580px){body{padding:9px}.top,.panel,.hero{padding:14px}.filters{grid-template-columns:1fr 1fr}.stats{gap:8px}.stat{padding:12px}.stat strong{font-size:20px}}
</style>
</head>
<body>
<div class="wrap">

<header class="top">
    <div>
        <div class="brand">ASO<span>VERIFY</span></div>
        <div class="muted">DATA &amp; AIRTIME PLAN CONTROL CENTRE</div>
    </div>
    <div class="row">
        <span class="pill"><?= dpm_h($admin['name']) ?> · <?= dpm_h($rank) ?></span>
        <a class="btn secondary" href="/dashboard.php">Dashboard</a>
    </div>
</header>

<section class="hero panel">
    <h1>Plan &amp; Pricing Manager</h1>
    <div class="muted">
        Synchronize plans from Sabuss, maintain provider plan IDs, set customer prices,
        and control which services are available on ASOVERIFY.
    </div>
</section>

<?php if ($message !== ''): ?>
<div class="flash <?= $messageType === 'error' ? 'error' : '' ?>">
    <?= dpm_h($message) ?>
</div>
<?php endif; ?>

<section class="stats">
    <div class="stat"><small>Total plans</small><strong><?= $stats['total'] ?></strong></div>
    <div class="stat"><small>Active plans</small><strong><?= $stats['active'] ?></strong></div>
    <div class="stat"><small>Data plans</small><strong><?= $stats['data'] ?></strong></div>
    <div class="stat"><small>Airtime plans</small><strong><?= $stats['airtime'] ?></strong></div>
</section>

<div class="grid">
    <aside>
        <section class="panel">
            <h2>API Plan Synchronization</h2>
            <div class="muted">Fetch the provider's current plan list.</div>

            <?php foreach (['data' => 'Synchronize Data Plans', 'airtime' => 'Synchronize Airtime Plans'] as $cat => $label): ?>
            <form method="post">
                <input type="hidden" name="csrf_token" value="<?= dpm_h($csrf) ?>">
                <input type="hidden" name="action" value="sync">
                <input type="hidden" name="category" value="<?= dpm_h($cat) ?>">
                <button class="full" type="submit"><?= dpm_h($label) ?></button>
            </form>
            <?php endforeach; ?>

            <small class="note">
                Sync never deletes plans. New plans are added as inactive with a ₦0 selling
                price until you set a price. Existing custom prices are preserved unless a
                markup was saved for that plan.
            </small>
        </section>

        <section class="panel">
            <h2>Generate Selling Prices</h2>
            <div class="muted">Bulk update prices using saved provider costs.</div>
            <form method="post">
                <input type="hidden" name="csrf_token" value="<?= dpm_h($csrf) ?>">
                <input type="hidden" name="action" value="generate_prices">

                <label>Apply to</label>
                <select name="bulk_category">
                    <option value="all">Data and airtime</option>
                    <option value="data">Data only</option>
                    <option value="airtime">Airtime only</option>
                </select>

                <label>Markup method</label>
                <select name="bulk_type">
                    <option value="fixed">Fixed profit (₦)</option>
                    <option value="percent">Percentage markup (%)</option>
                </select>

                <label>Markup value</label>
                <input name="bulk_value" type="number" min="0" step="0.01" value="20" required>

                <button type="submit" class="full"
                    onclick="return confirm('Regenerate prices for plans with a saved provider cost?')">
                    Generate New Selling Prices
                </button>
            </form>
            <small class="note">
                Example: provider cost ₦500 + fixed markup ₦50 = selling price ₦550.
                Percentage markup of 10% on ₦500 = ₦550.
            </small>
        </section>

        <section class="panel">
            <h2>Add a Plan Manually</h2>
            <form method="post">
                <input type="hidden" name="csrf_token" value="<?= dpm_h($csrf) ?>">
                <input type="hidden" name="action" value="save_plan">
                <input type="hidden" name="id" value="0">

                <label>Category</label>
                <select name="category" required>
                    <option value="data">Data</option>
                    <option value="airtime">Airtime</option>
                </select>

                <label>Network</label>
                <select name="network" required>
                    <option value="MTN">MTN</option>
                    <option value="AIRTEL">Airtel</option>
                    <option value="GLO">Glo</option>
                    <option value="9MOBILE">9mobile</option>
                    <option value="SMILE">Smile</option>
                    <option value="OTHER">Other</option>
                </select>

                <label>Provider API Plan ID</label>
                <input type="number" name="plan_id" min="1" required placeholder="e.g. 2370">

                <label>Plan name</label>
                <input name="plan_name" required placeholder="e.g. MTN SME 5GB">

                <label>Provider cost (₦)</label>
                <input name="cost_price" type="number" min="0" step="0.01" value="0" required>

                <label>Markup type</label>
                <select name="markup_type">
                    <option value="fixed">Fixed profit (₦)</option>
                    <option value="percent">Percentage (%)</option>
                </select>

                <label>Markup value</label>
                <input name="markup_value" type="number" min="0" step="0.01" value="0" required>

                <label>Selling price (₦)</label>
                <input name="selling_price" type="number" min="0" step="0.01" value="0" required>

                <label>Status</label>
                <select name="status">
                    <option value="inactive">Inactive</option>
                    <option value="active">Active</option>
                </select>

                <label style="text-transform:none">
                    <input type="checkbox" name="auto_price" value="1" style="width:auto;min-height:0">
                    Calculate selling price from cost and markup
                </label>

                <button type="submit" class="full">Save New Plan</button>
            </form>
        </section>
    </aside>

    <main class="panel">
        <h2>Existing Plans</h2>
        <div class="muted">Edit the API plan ID, price, cost, markup, and status.</div>

        <form method="get" class="filters">
            <select name="category">
                <option value="all">All categories</option>
                <option value="data" <?= $filterCategory === 'data' ? 'selected' : '' ?>>Data</option>
                <option value="airtime" <?= $filterCategory === 'airtime' ? 'selected' : '' ?>>Airtime</option>
            </select>

            <select name="network">
                <option value="">All networks</option>
                <?php foreach ($networks as $network): ?>
                <option value="<?= dpm_h($network) ?>" <?= $filterNetwork === $network ? 'selected' : '' ?>>
                    <?= dpm_h($network) ?>
                </option>
                <?php endforeach; ?>
            </select>

            <select name="status">
                <option value="all">All statuses</option>
                <option value="active" <?= $filterStatus === 'active' ? 'selected' : '' ?>>Active</option>
                <option value="inactive" <?= $filterStatus === 'inactive' ? 'selected' : '' ?>>Inactive</option>
            </select>

            <input name="q" value="<?= dpm_h($search) ?>" placeholder="Search name or API ID">
            <button type="submit">Search Plans</button>
        </form>

        <?php if (!$plans): ?>
            <div class="empty">No matching plans found.</div>
        <?php else: ?>
        <div class="table-wrap">
            <table>
                <thead>
                <tr>
                    <th>Plan</th>
                    <th>Network / Type</th>
                    <th>API Plan ID</th>
                    <th>Provider cost</th>
                    <th>Selling price</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($plans as $p): ?>
                <tr>
                    <td>
                        <strong><?= dpm_h($p['plan_name']) ?></strong>
                        <span class="muted">Local ID: <?= (int)$p['id'] ?></span>
                    </td>
                    <td>
                        <?= dpm_h($p['network']) ?><br>
                        <span class="muted"><?= dpm_h(strtoupper((string)$p['category'])) ?></span>
                    </td>
                    <td><strong><?= (int)$p['plan_id'] ?></strong></td>
                    <td><?= dpm_money($p['cost_price']) ?></td>
                    <td class="price"><?= dpm_money($p['selling_price']) ?></td>
                    <td>
                        <span class="tag <?= strtolower((string)$p['status']) === 'active' ? 'active' : 'inactive' ?>">
                            <?= dpm_h($p['status']) ?>
                        </span>
                    </td>
                    <td>
                        <div class="actions">
                            <button type="button" class="small"
                                onclick='editPlan(<?= json_encode([
                                    'id' => (int)$p['id'],
                                    'category' => strtolower((string)$p['category']),
                                    'network' => (string)$p['network'],
                                    'plan_id' => (int)$p['plan_id'],
                                    'plan_name' => (string)$p['plan_name'],
                                    'cost_price' => (float)$p['cost_price'],
                                    'markup_type' => (string)$p['markup_type'],
                                    'markup_value' => (float)$p['markup_value'],
                                    'selling_price' => (float)$p['selling_price'],
                                    'status' => strtolower((string)$p['status'])
                                ], JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>)'>
                                Edit
                            </button>
                            <form method="post" onsubmit="return confirm('Change this plan status?')">
                                <input type="hidden" name="csrf_token" value="<?= dpm_h($csrf) ?>">
                                <input type="hidden" name="action" value="toggle">
                                <input type="hidden" name="id" value="<?= (int)$p['id'] ?>">
                                <button type="submit" class="small secondary">
                                    <?= strtolower((string)$p['status']) === 'active' ? 'Deactivate' : 'Activate' ?>
                                </button>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </main>
</div>

<!-- Edit modal -->
<div id="editModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.78);z-index:50;overflow:auto;padding:15px">
    <div class="panel" style="max-width:600px;margin:25px auto">
        <div class="row" style="justify-content:space-between">
            <h2>Edit Plan</h2>
            <button type="button" class="secondary" onclick="closeEdit()">Close</button>
        </div>

        <form method="post" id="editForm">
            <input type="hidden" name="csrf_token" value="<?= dpm_h($csrf) ?>">
            <input type="hidden" name="action" value="save_plan">
            <input type="hidden" name="id" id="e_id">

            <label>Category</label>
            <select name="category" id="e_category">
                <option value="data">Data</option>
                <option value="airtime">Airtime</option>
            </select>

            <label>Network</label>
            <input name="network" id="e_network" required>

            <label>Provider API plan ID</label>
            <input name="plan_id" id="e_plan_id" type="number" min="1" required>

            <label>Plan name</label>
            <input name="plan_name" id="e_plan_name" required>

            <label>Provider cost (₦)</label>
            <input name="cost_price" id="e_cost_price" type="number" min="0" step="0.01" required>

            <label>Markup type</label>
            <select name="markup_type" id="e_markup_type">
                <option value="fixed">Fixed profit (₦)</option>
                <option value="percent">Percentage (%)</option>
            </select>

            <label>Markup value</label>
            <input name="markup_value" id="e_markup_value" type="number" min="0" step="0.01" required>

            <label>Selling price (₦)</label>
            <input name="selling_price" id="e_selling_price" type="number" min="0" step="0.01" required>

            <label>Status</label>
            <select name="status" id="e_status">
                <option value="active">Active</option>
                <option value="inactive">Inactive</option>
            </select>

            <label style="text-transform:none">
                <input type="checkbox" name="auto_price" value="1" style="width:auto;min-height:0">
                Recalculate selling price from cost and markup
            </label>

            <button class="full" type="submit">Save Plan Changes</button>
        </form>
    </div>
</div>

<script>
function editPlan(p) {
    document.getElementById('e_id').value = p.id;
    document.getElementById('e_category').value = p.category;
    document.getElementById('e_network').value = p.network;
    document.getElementById('e_plan_id').value = p.plan_id;
    document.getElementById('e_plan_name').value = p.plan_name;
    document.getElementById('e_cost_price').value = p.cost_price;
    document.getElementById('e_markup_type').value = p.markup_type || 'fixed';
    document.getElementById('e_markup_value').value = p.markup_value;
    document.getElementById('e_selling_price').value = p.selling_price;
    document.getElementById('e_status').value = p.status;
    document.getElementById('editModal').style.display = 'block';
}

function closeEdit() {
    document.getElementById('editModal').style.display = 'none';
}

document.getElementById('editModal').addEventListener('click', function (e) {
    if (e.target === this) closeEdit();
});
</script>
</div>
</body>
</html>
