<?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)) {
    include($config_path);
} else {
    echo json_encode(['status' => '0', 'msg' => 'Configuration file not found']);
    exit();
}

// Admin guard
$stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :user_id");
$stmt->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
$stmt->execute();
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin || $admin['is_admin'] != 1) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized access']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']);
    exit();
}

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

// ─── ADD API ──────────────────────────────────────────────────────────────────
if ($action === 'add') {
    $api_name = isset($_POST['api_name']) ? trim($_POST['api_name']) : '';
    $api_url  = isset($_POST['api_url'])  ? trim($_POST['api_url'])  : '';
    $api_key  = isset($_POST['api_key'])  ? trim($_POST['api_key'])  : '';
    $allowed_types = ['smscodes', 'smspva', '5sim', 'smsbus'];
    $api_type = isset($_POST['api_type']) && in_array($_POST['api_type'], $allowed_types)
                ? $_POST['api_type'] : 'smscodes';

    if (empty($api_name) || empty($api_url) || empty($api_key)) {
        echo json_encode(['status' => '0', 'msg' => 'All fields are required']);
        exit();
    }

    if (!filter_var($api_url, FILTER_VALIDATE_URL)) {
        echo json_encode(['status' => '0', 'msg' => 'Please enter a valid API URL']);
        exit();
    }

    try {
        $stmt = $pdo->prepare(
            "INSERT INTO api_detail (api_name, api_url, api_key, api_code, api_type)
             VALUES (:api_name, :api_url, :api_key, '1', :api_type)"
        );
        $stmt->bindParam(':api_name', $api_name, PDO::PARAM_STR);
        $stmt->bindParam(':api_url',  $api_url,  PDO::PARAM_STR);
        $stmt->bindParam(':api_key',  $api_key,  PDO::PARAM_STR);
        $stmt->bindParam(':api_type', $api_type, PDO::PARAM_STR);

        if ($stmt->execute()) {
            $labels = ['smspva' => 'Server1 (SMSPVA)', 'smscodes' => 'Server2 (SMSCodes)', '5sim' => 'Server3 (5SIM)', 'smsbus' => 'Server4 (SMS-Bus)'];
            $label  = $labels[$api_type] ?? $api_type;
            echo json_encode(['status' => '1', 'msg' => "API \"{$api_name}\" ({$label}) added successfully."]);
        } else {
            echo json_encode(['status' => '0', 'msg' => 'Failed to add API']);
        }
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    }

// ─── EDIT API ─────────────────────────────────────────────────────────────────
} elseif ($action === 'edit') {
    $id       = filter_var($_POST['id'] ?? '', FILTER_VALIDATE_INT);
    $api_name = isset($_POST['api_name']) ? trim($_POST['api_name']) : '';
    $api_url  = isset($_POST['api_url'])  ? trim($_POST['api_url'])  : '';
    $api_key  = isset($_POST['api_key'])  ? trim($_POST['api_key'])  : '';
    $allowed_types = ['smscodes', 'smspva', '5sim', 'smsbus'];
    $api_type = isset($_POST['api_type']) && in_array($_POST['api_type'], $allowed_types)
                ? $_POST['api_type'] : 'smscodes';

    if (!$id) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid API ID']); exit();
    }
    if (empty($api_name) || empty($api_url) || empty($api_key)) {
        echo json_encode(['status' => '0', 'msg' => 'All fields are required']); exit();
    }
    if (!filter_var($api_url, FILTER_VALIDATE_URL)) {
        echo json_encode(['status' => '0', 'msg' => 'Please enter a valid API URL']); exit();
    }

    try {
        $check = $pdo->prepare("SELECT id FROM api_detail WHERE id = :id");
        $check->bindParam(':id', $id, PDO::PARAM_INT);
        $check->execute();
        if (!$check->fetch()) {
            echo json_encode(['status' => '0', 'msg' => 'API not found']); exit();
        }

        $stmt = $pdo->prepare(
            "UPDATE api_detail SET api_name=:api_name, api_url=:api_url, api_key=:api_key, api_type=:api_type
              WHERE id=:id"
        );
        $stmt->bindParam(':api_name', $api_name, PDO::PARAM_STR);
        $stmt->bindParam(':api_url',  $api_url,  PDO::PARAM_STR);
        $stmt->bindParam(':api_key',  $api_key,  PDO::PARAM_STR);
        $stmt->bindParam(':api_type', $api_type, PDO::PARAM_STR);
        $stmt->bindParam(':id',       $id,       PDO::PARAM_INT);

        if ($stmt->execute()) {
            echo json_encode(['status' => '1', 'msg' => "API \"{$api_name}\" updated successfully."]);
        } else {
            echo json_encode(['status' => '0', 'msg' => 'Failed to update API']);
        }
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    }

// ─── DELETE API ───────────────────────────────────────────────────────────────
} elseif ($action === 'delete') {
    $id = filter_var($_POST['id'] ?? '', FILTER_VALIDATE_INT);
    if (!$id) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid API ID']); exit();
    }

    try {
        $check = $pdo->prepare("SELECT api_name FROM api_detail WHERE id = :id");
        $check->bindParam(':id', $id, PDO::PARAM_INT);
        $check->execute();
        $api = $check->fetch(PDO::FETCH_ASSOC);
        if (!$api) {
            echo json_encode(['status' => '0', 'msg' => 'API not found']); exit();
        }

        $stmt = $pdo->prepare("DELETE FROM api_detail WHERE id = :id");
        $stmt->bindParam(':id', $id, PDO::PARAM_INT);
        if ($stmt->execute()) {
            echo json_encode(['status' => '1', 'msg' => "API \"{$api['api_name']}\" deleted successfully."]);
        } else {
            echo json_encode(['status' => '0', 'msg' => 'Failed to delete API']);
        }
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    }

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