<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: application/json');

$config_path = dirname(__DIR__, 2) . '/include/config.php';
if (!file_exists($config_path)) {
    echo json_encode(['status'=>'0','msg'=>'Config error']); exit();
}
include($config_path);

// Admin check
$stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :id");
$stmt->execute(['id' => $_SESSION['user_id'] ?? 0]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$admin || $admin['is_admin'] != 1) {
    echo json_encode(['status'=>'0','msg'=>'Unauthorized']); exit();
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status'=>'0','msg'=>'Invalid request']); exit();
}

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

// ── Save CheapDataHub settings ────────────────────────────────────────────────
if ($action === 'save_cdh_settings') {
    $fields = [
        'cdh_api_key'            => trim($_POST['cdh_api_key']           ?? ''),
        'cdh_api_url'            => trim($_POST['cdh_api_url']            ?? 'https://www.cheapdatahub.ng/api/v1/resellers'),
        'cdh_enabled'            => (int)($_POST['cdh_enabled']           ?? 0),
        'cdh_airtime_markup'     => (float)($_POST['cdh_airtime_markup']  ?? 0),
        'cdh_cable_markup'       => (float)($_POST['cdh_cable_markup']    ?? 0),
        'cdh_electricity_markup' => (float)($_POST['cdh_electricity_markup'] ?? 0),
    ];

    $set_parts = [];
    foreach (array_keys($fields) as $k) {
        $set_parts[] = "`$k` = :$k";
    }
    $sets = implode(', ', $set_parts);
    $stmt = $pdo->prepare("UPDATE settings SET $sets WHERE id = 1");
    foreach ($fields as $k => $v) $stmt->bindValue(":$k", $v);

    if ($stmt->execute()) {
        echo json_encode(['status'=>'1','msg'=>'CheapDataHub settings saved successfully.']);
    } else {
        echo json_encode(['status'=>'0','msg'=>'Failed to save settings.']);
    }
    exit();
}

// ── Test CheapDataHub connection ──────────────────────────────────────────────
if ($action === 'test_cdh') {
    $api_key = trim($site_data['cdh_api_key'] ?? '');
    if (empty($api_key)) {
        echo json_encode(['status'=>'0','msg'=>'No API key configured. Save settings first.']); exit();
    }

    $cdh_inc = dirname(__DIR__, 2) . '/include/CheapDataHub.php';
    if (!file_exists($cdh_inc)) {
        echo json_encode(['status'=>'0','msg'=>'CheapDataHub.php class file not found in /include/']); exit();
    }
    include_once($cdh_inc);

    $cdh    = new CheapDataHub($api_key, 'https://www.cheapdatahub.ng/api/v1/resellers');
    $result = $cdh->getBalance();

    if ($result['success']) {
        $bal = $result['data']['balance'] ?? $result['data']['wallet_balance'] ?? 'N/A';
        echo json_encode(['status'=>'1','msg'=>'✅ Connection successful! CDH Balance: ' . $bal]);
    } else {
        $raw = isset($result['data']) ? ' | Response: ' . json_encode($result['data']) : '';
        echo json_encode(['status'=>'0','msg'=>'Connection failed: ' . ($result['error'] ?? 'Unknown error') . $raw]);
    }
    exit();
}

// ── Add Data Plan ──────────────────────────────────────────────────────────────
if ($action === 'add_data_plan') {
    $network   = strtoupper(trim($_POST['network']   ?? ''));
    $plan_name = trim($_POST['plan_name']            ?? '');
    $data_size = trim($_POST['data_size']            ?? '');
    $validity  = trim($_POST['validity']             ?? '');
    $plan_id   = trim($_POST['plan_id']              ?? '');
    $plan_type = strtoupper(trim($_POST['plan_type'] ?? 'DAILY'));  // Changed default
    $cost      = (float)($_POST['cost_price']        ?? 0);
    $sell      = (float)($_POST['sell_price']        ?? 0);
    $status    = (int)($_POST['status']              ?? 1);

    if (!$network || !$plan_name || !$data_size || !$validity || !$plan_id || $sell <= 0) {
        echo json_encode(['status'=>'0','msg'=>'All required fields must be filled. Sell price must be > 0.']); exit();
    }
    if (!is_numeric($plan_id)) {
        echo json_encode(['status'=>'0','msg'=>'Plan ID (CDH bundle_id) must be a number.']); exit();
    }

    try {
        $pdo->prepare(
            "INSERT INTO vtu_data_plans (network, plan_name, data_size, validity, plan_id, plan_type, cost_price, sell_price, status)
             VALUES (:network, :plan_name, :data_size, :validity, :plan_id, :plan_type, :cost, :sell, :status)"
        )->execute(compact('network','plan_name','data_size','validity','plan_id','plan_type','cost','sell','status'));
        echo json_encode(['status'=>'1','msg'=>"Plan \"{$plan_name}\" added successfully."]);
    } catch (PDOException $e) {
        echo json_encode(['status'=>'0','msg'=>'Database error: '.$e->getMessage()]);
    }
    exit();
}

// ── Edit Data Plan ─────────────────────────────────────────────────────────────
if ($action === 'edit_data_plan') {
    $id        = (int)($_POST['id']          ?? 0);
    $network   = strtoupper(trim($_POST['network']   ?? ''));
    $plan_name = trim($_POST['plan_name']            ?? '');
    $data_size = trim($_POST['data_size']            ?? '');
    $validity  = trim($_POST['validity']             ?? '');
    $plan_id   = trim($_POST['plan_id']              ?? '');
    $plan_type = strtoupper(trim($_POST['plan_type'] ?? 'DAILY'));  // Changed default
    $cost      = (float)($_POST['cost_price']        ?? 0);
    $sell      = (float)($_POST['sell_price']        ?? 0);
    $status    = (int)($_POST['status']              ?? 1);

    if (!$id || !$plan_name || $sell <= 0) {
        echo json_encode(['status'=>'0','msg'=>'Required fields missing.']); exit();
    }
    try {
        $pdo->prepare(
            "UPDATE vtu_data_plans SET network=:network, plan_name=:plan_name, data_size=:data_size,
             validity=:validity, plan_id=:plan_id, plan_type=:plan_type,
             cost_price=:cost, sell_price=:sell, status=:status WHERE id=:id"
        )->execute(compact('network','plan_name','data_size','validity','plan_id','plan_type','cost','sell','status','id'));
        echo json_encode(['status'=>'1','msg'=>'Plan updated successfully.']);
    } catch (PDOException $e) {
        echo json_encode(['status'=>'0','msg'=>'Database error: '.$e->getMessage()]);
    }
    exit();
}

// ── Delete Data Plan ───────────────────────────────────────────────────────────
if ($action === 'delete_data_plan') {
    $id = (int)($_POST['id'] ?? 0);
    if (!$id) { echo json_encode(['status'=>'0','msg'=>'Invalid ID']); exit(); }
    $check = $pdo->prepare("SELECT plan_name FROM vtu_data_plans WHERE id=:id");
    $check->execute(['id'=>$id]);
    $row = $check->fetch(PDO::FETCH_ASSOC);
    if (!$row) { echo json_encode(['status'=>'0','msg'=>'Plan not found']); exit(); }
    $pdo->prepare("DELETE FROM vtu_data_plans WHERE id=:id")->execute(['id'=>$id]);
    echo json_encode(['status'=>'1','msg'=>"Plan \"{$row['plan_name']}\" deleted."]);
    exit();
}

// ── Add Cable Plan ─────────────────────────────────────────────────────────────
if ($action === 'add_cable_plan') {
    $provider  = strtoupper(trim($_POST['provider']  ?? ''));
    $plan_name = trim($_POST['plan_name']            ?? '');
    $plan_code = trim($_POST['plan_code']            ?? '');
    $sell      = (float)($_POST['sell_price']        ?? 0);
    $status    = (int)($_POST['status']              ?? 1);

    if (!$provider || !$plan_name || !$plan_code || $sell <= 0) {
        echo json_encode(['status'=>'0','msg'=>'All fields are required. Sell price must be > 0.']); exit();
    }
    try {
        $pdo->prepare(
            "INSERT INTO vtu_cable_plans (provider, plan_name, plan_code, sell_price, status) VALUES (:p,:n,:c,:s,:st)"
        )->execute(['p'=>$provider,'n'=>$plan_name,'c'=>$plan_code,'s'=>$sell,'st'=>$status]);
        echo json_encode(['status'=>'1','msg'=>"Cable plan \"{$plan_name}\" added."]);
    } catch (PDOException $e) {
        echo json_encode(['status'=>'0','msg'=>'Database error: '.$e->getMessage()]);
    }
    exit();
}

// ── Edit Cable Plan ────────────────────────────────────────────────────────────
if ($action === 'edit_cable_plan') {
    $id       = (int)($_POST['id']          ?? 0);
    $provider = strtoupper(trim($_POST['provider']   ?? ''));
    $name     = trim($_POST['plan_name']    ?? '');
    $code     = trim($_POST['plan_code']    ?? '');
    $sell     = (float)($_POST['sell_price']?? 0);
    $status   = (int)($_POST['status']      ?? 1);

    if (!$id || !$name || $sell <= 0) { echo json_encode(['status'=>'0','msg'=>'Missing fields']); exit(); }
    $pdo->prepare("UPDATE vtu_cable_plans SET provider=:p, plan_name=:n, plan_code=:c, sell_price=:s, status=:st WHERE id=:id")
        ->execute(['p'=>$provider,'n'=>$name,'c'=>$code,'s'=>$sell,'st'=>$status,'id'=>$id]);
    echo json_encode(['status'=>'1','msg'=>'Cable plan updated.']);
    exit();
}

// ── Delete Cable Plan ──────────────────────────────────────────────────────────
if ($action === 'delete_cable_plan') {
    $id = (int)($_POST['id'] ?? 0);
    if (!$id) { echo json_encode(['status'=>'0','msg'=>'Invalid ID']); exit(); }
    $check = $pdo->prepare("SELECT plan_name FROM vtu_cable_plans WHERE id=:id");
    $check->execute(['id'=>$id]);
    $row = $check->fetch(PDO::FETCH_ASSOC);
    if (!$row) { echo json_encode(['status'=>'0','msg'=>'Plan not found']); exit(); }
    $pdo->prepare("DELETE FROM vtu_cable_plans WHERE id=:id")->execute(['id'=>$id]);
    echo json_encode(['status'=>'1','msg'=>"Plan \"{$row['plan_name']}\" deleted."]);
    exit();
}

// ── Recent VTU transactions (paginated + filtered) ────────────────────────────
if ($action === 'get_transactions') {
    $page     = max(1, (int)($_POST['page']     ?? 1));
    $per_page = max(5, min(100, (int)($_POST['per_page'] ?? 20)));
    $offset   = ($page - 1) * $per_page;

    $status   = trim($_POST['status']   ?? '');
    $svc_type = trim($_POST['svc_type'] ?? '');

    // Build WHERE clause
    $where  = [];
    $params = [];

    if ($status !== '') {
        $where[]          = 'vh.status = :status';
        $params[':status'] = $status;
    }
    if ($svc_type !== '') {
        $where[]            = 'vh.service_type = :svc_type';
        $params[':svc_type'] = $svc_type;
    }

    $whereSQL = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

    try {
        // Total count
        $countStmt = $pdo->prepare(
            "SELECT COUNT(*) FROM vtu_history vh $whereSQL"
        );
        $countStmt->execute($params);
        $total = (int)$countStmt->fetchColumn();

        $total_pages = max(1, (int)ceil($total / $per_page));

        // Data rows
        $dataStmt = $pdo->prepare(
            "SELECT vh.*, u.username
             FROM vtu_history vh
             LEFT JOIN users u ON u.id = vh.user_id
             $whereSQL
             ORDER BY vh.id DESC
             LIMIT :limit OFFSET :offset"
        );
        foreach ($params as $k => $v) $dataStmt->bindValue($k, $v);
        $dataStmt->bindValue(':limit',  $per_page, PDO::PARAM_INT);
        $dataStmt->bindValue(':offset', $offset,   PDO::PARAM_INT);
        $dataStmt->execute();

        $rows = $dataStmt->fetchAll(PDO::FETCH_ASSOC);

        echo json_encode([
            'status'      => '1',
            'data'        => $rows,
            'total'       => $total,
            'page'        => $page,
            'per_page'    => $per_page,
            'total_pages' => $total_pages,
        ]);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'DB error: ' . $e->getMessage()]);
    }
    exit();
}

echo json_encode(['status'=>'0','msg'=>'Unknown action']);