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

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

header('Content-Type: application/json');

// Load config
$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();
}

// Verify admin status
$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 SERVICE ──────────────────────────────────────────────────────────────
if ($action === 'add') {
    $service_name  = isset($_POST['service_name'])  ? trim($_POST['service_name'])  : '';
    $service_id    = isset($_POST['service_id'])    ? trim($_POST['service_id'])    : '';
    $service_price = isset($_POST['service_price']) ? trim($_POST['service_price']) : '';
    $server_id     = filter_var($_POST['server_id'] ?? '', FILTER_VALIDATE_INT);
    $status        = isset($_POST['status']) && in_array($_POST['status'], ['0', '1']) ? $_POST['status'] : '1';

    if (empty($service_name) || empty($service_id) || empty($service_price) || !$server_id) {
        echo json_encode(['status' => '0', 'msg' => 'All fields are required']);
        exit();
    }

    $service_price = filter_var($service_price, FILTER_VALIDATE_FLOAT);
    if ($service_price === false || $service_price < 0) {
        echo json_encode(['status' => '0', 'msg' => 'Please enter a valid service price']);
        exit();
    }

    try {
        // Verify the country/server exists
        $check = $pdo->prepare("SELECT id FROM otp_server WHERE id = :id");
        $check->bindParam(':id', $server_id, PDO::PARAM_INT);
        $check->execute();
        if (!$check->fetch()) {
            echo json_encode(['status' => '0', 'msg' => 'Selected country not found']);
            exit();
        }

        $stmt = $pdo->prepare("INSERT INTO service (service_name, service_id, server_id, service_price, status) VALUES (:service_name, :service_id, :server_id, :service_price, :status)");
        $stmt->bindParam(':service_name',  $service_name,  PDO::PARAM_STR);
        $stmt->bindParam(':service_id',    $service_id,    PDO::PARAM_STR);
        $stmt->bindParam(':server_id',     $server_id,     PDO::PARAM_INT);
        $stmt->bindParam(':service_price', $service_price, PDO::PARAM_STR);
        $stmt->bindParam(':status',        $status,        PDO::PARAM_STR);

        if ($stmt->execute()) {
            echo json_encode(['status' => '1', 'msg' => '"' . $service_name . '" service has been added successfully']);
        } else {
            echo json_encode(['status' => '0', 'msg' => 'Failed to add service']);
        }
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    }

// ─── EDIT SERVICE ─────────────────────────────────────────────────────────────
} elseif ($action === 'edit') {
    $id            = filter_var($_POST['id']         ?? '', FILTER_VALIDATE_INT);
    $service_name  = isset($_POST['service_name'])   ? trim($_POST['service_name'])  : '';
    $service_id    = isset($_POST['service_id'])     ? trim($_POST['service_id'])    : '';
    $service_price = isset($_POST['service_price'])  ? trim($_POST['service_price']) : '';
    $server_id     = filter_var($_POST['server_id']  ?? '', FILTER_VALIDATE_INT);
    $status        = isset($_POST['status']) && in_array($_POST['status'], ['0', '1']) ? $_POST['status'] : '1';

    if (!$id) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid service ID']);
        exit();
    }

    if (empty($service_name) || empty($service_id) || empty($service_price) || !$server_id) {
        echo json_encode(['status' => '0', 'msg' => 'All fields are required']);
        exit();
    }

    $service_price = filter_var($service_price, FILTER_VALIDATE_FLOAT);
    if ($service_price === false || $service_price < 0) {
        echo json_encode(['status' => '0', 'msg' => 'Please enter a valid service price']);
        exit();
    }

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

        // Verify country exists
        $check2 = $pdo->prepare("SELECT id FROM otp_server WHERE id = :id");
        $check2->bindParam(':id', $server_id, PDO::PARAM_INT);
        $check2->execute();
        if (!$check2->fetch()) {
            echo json_encode(['status' => '0', 'msg' => 'Selected country not found']);
            exit();
        }

        $stmt = $pdo->prepare("UPDATE service SET service_name = :service_name, service_id = :service_id, server_id = :server_id, service_price = :service_price, status = :status WHERE id = :id");
        $stmt->bindParam(':service_name',  $service_name,  PDO::PARAM_STR);
        $stmt->bindParam(':service_id',    $service_id,    PDO::PARAM_STR);
        $stmt->bindParam(':server_id',     $server_id,     PDO::PARAM_INT);
        $stmt->bindParam(':service_price', $service_price, PDO::PARAM_STR);
        $stmt->bindParam(':status',        $status,        PDO::PARAM_STR);
        $stmt->bindParam(':id',            $id,            PDO::PARAM_INT);

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

// ─── DELETE SERVICE ───────────────────────────────────────────────────────────
} elseif ($action === 'delete') {
    $id = filter_var($_POST['id'] ?? '', FILTER_VALIDATE_INT);

    if (!$id) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid service ID']);
        exit();
    }

    try {
        // Get name for response message
        $check = $pdo->prepare("SELECT service_name FROM service WHERE id = :id");
        $check->bindParam(':id', $id, PDO::PARAM_INT);
        $check->execute();
        $service = $check->fetch(PDO::FETCH_ASSOC);

        if (!$service) {
            echo json_encode(['status' => '0', 'msg' => 'Service not found']);
            exit();
        }

        $stmt = $pdo->prepare("DELETE FROM service WHERE id = :id");
        $stmt->bindParam(':id', $id, PDO::PARAM_INT);

        if ($stmt->execute()) {
            echo json_encode(['status' => '1', 'msg' => '"' . $service['service_name'] . '" service has been deleted successfully']);
        } else {
            echo json_encode(['status' => '0', 'msg' => 'Failed to delete service']);
        }
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    }

// ─── DELETE ALL SERVICES ─────────────────────────────────────────────────────
} elseif ($action === 'delete_all') {
    try {
        $count = (int)$pdo->query("SELECT COUNT(*) FROM service")->fetchColumn();
        $pdo->exec("DELETE FROM service");
        echo json_encode(['status' => '1', 'msg' => "All {$count} SMS services have been deleted."]);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    }

// ─── GET SERVICES BY COUNTRY ──────────────────────────────────────────────────
} elseif ($action === 'get_by_country') {
    $server_id = filter_var($_POST['server_id'] ?? '', FILTER_VALIDATE_INT);

    if (!$server_id) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid country ID']);
        exit();
    }

    try {
        $stmt = $pdo->prepare("
            SELECT s.*, o.server_name, o.flag_url, ad.api_type AS provider
            FROM service s
            LEFT JOIN otp_server o ON s.server_id = o.id
            LEFT JOIN api_detail ad ON ad.id = o.api_id
            WHERE s.server_id = :server_id
            ORDER BY s.service_name ASC
        ");
        $stmt->bindParam(':server_id', $server_id, PDO::PARAM_INT);
        $stmt->execute();
        $services = $stmt->fetchAll(PDO::FETCH_ASSOC);

        echo json_encode(['status' => '1', 'services' => $services]);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    }

// ─── UNKNOWN ACTION ───────────────────────────────────────────────────────────
} else {
    echo json_encode(['status' => '0', 'msg' => 'Unknown action']);
}
?>