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

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit();
}

// Bootstrap config (goes up two levels: ajax/ -> admin/ -> public_html/)
require_once __DIR__ . '/../../include/config.php';

// Must be logged in as admin
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true ||
    !isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized access.']);
    exit();
}

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

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

switch ($action) {

    // ─── ADD ─────────────────────────────────────────────────────────────
    case 'add':
        $server_name = trim($_POST['server_name'] ?? '');
        $server_code = trim($_POST['server_code'] ?? '');
        $flag_url    = trim($_POST['flag_url']    ?? '');
        $api_id      = (int)($_POST['api_id']     ?? 0);
        $status      = in_array($_POST['status'] ?? '', ['0', '1']) ? $_POST['status'] : '1';

        if (empty($server_name) || empty($server_code) || $api_id <= 0) {
            echo json_encode(['status' => '0', 'msg' => 'Country Name, Country Code and API are required.']);
            exit();
        }

        try {
            $stmt = $pdo->prepare(
                "INSERT INTO otp_server (server_name, server_code, flag_url, api_id, status)
                 VALUES (:server_name, :server_code, :flag_url, :api_id, :status)"
            );
            $stmt->execute([
                ':server_name' => $server_name,
                ':server_code' => $server_code,
                ':flag_url'    => $flag_url,
                ':api_id'      => $api_id,
                ':status'      => $status,
            ]);
            echo json_encode(['status' => '1', 'msg' => "Country \"$server_name\" added successfully."]);
        } catch (PDOException $e) {
            error_log("ajax/countries.php add error: " . $e->getMessage());
            echo json_encode(['status' => '0', 'msg' => 'Database error. Please try again.']);
        }
        break;

    // ─── EDIT ────────────────────────────────────────────────────────────
    case 'edit':
        $id          = (int)($_POST['id']          ?? 0);
        $server_name = trim($_POST['server_name']  ?? '');
        $server_code = trim($_POST['server_code']  ?? '');
        $flag_url    = trim($_POST['flag_url']     ?? '');
        $api_id      = (int)($_POST['api_id']      ?? 0);
        $status      = in_array($_POST['status'] ?? '', ['0', '1']) ? $_POST['status'] : '1';

        if ($id <= 0 || empty($server_name) || empty($server_code) || $api_id <= 0) {
            echo json_encode(['status' => '0', 'msg' => 'Country Name, Country Code and API are required.']);
            exit();
        }

        try {
            $stmt = $pdo->prepare(
                "UPDATE otp_server
                 SET server_name = :server_name,
                     server_code = :server_code,
                     flag_url    = :flag_url,
                     api_id      = :api_id,
                     status      = :status
                 WHERE id = :id"
            );
            $stmt->execute([
                ':server_name' => $server_name,
                ':server_code' => $server_code,
                ':flag_url'    => $flag_url,
                ':api_id'      => $api_id,
                ':status'      => $status,
                ':id'          => $id,
            ]);
            echo json_encode(['status' => '1', 'msg' => "Country \"$server_name\" updated successfully."]);
        } catch (PDOException $e) {
            error_log("ajax/countries.php edit error: " . $e->getMessage());
            echo json_encode(['status' => '0', 'msg' => 'Database error. Please try again.']);
        }
        break;

    // ─── DELETE ──────────────────────────────────────────────────────────
    case 'delete':
        $id = (int)($_POST['id'] ?? 0);

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

        try {
            // Fetch name first for the success message
            $fetch = $pdo->prepare("SELECT server_name FROM otp_server WHERE id = :id");
            $fetch->execute([':id' => $id]);
            $row = $fetch->fetch(PDO::FETCH_ASSOC);

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

            $stmt = $pdo->prepare("DELETE FROM otp_server WHERE id = :id");
            $stmt->execute([':id' => $id]);
            echo json_encode(['status' => '1', 'msg' => "Country \"{$row['server_name']}\" deleted successfully."]);
        } catch (PDOException $e) {
            error_log("ajax/countries.php delete error: " . $e->getMessage());
            echo json_encode(['status' => '0', 'msg' => 'Database error. Please try again.']);
        }
        break;

    // ─── UNKNOWN ACTION ──────────────────────────────────────────────────
    default:
        echo json_encode(['status' => '0', 'msg' => 'Unknown action.']);
        break;
}