<?php
try {

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

    include_once dirname(__DIR__, 2) . "/config/dbcon.php";
    include_once dirname(__DIR__, 2) . "/helpers/api_helper.php";

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        sendResponse(405, "Method Not Allowed");
    }

    $countryName = $_POST['country_name'] ?? null;
    $countryCurrency = $_POST['country_currency'] ?? null;
    $countryCode = $_POST['country_code'] ?? null;
    $countryImage = $_FILES['country_image'] ?? null;

    if (!$countryName || !$countryCurrency || !$countryCode) {
        sendResponse(400, "Country Name, Currency and Code are required");
    }

    $fileName = null;

    if ($countryImage && $countryImage['error'] === 0) {

        $allowedTypes = ['jpg', 'jpeg', 'png', 'webp'];
        $ext = strtolower(pathinfo($countryImage['name'], PATHINFO_EXTENSION));
        $maxSize = 2 * 1024 * 1024; // 2MB

        if (!in_array($ext, $allowedTypes)) {
            sendResponse(400, "Invalid image type");
        }

        if ($countryImage['size'] > $maxSize) {
            sendResponse(400, "File size must be less than 2MB");
        }

        $upload_path = dirname(__DIR__, 2) . "/uploads/country_icon/";
        $fileName = time() . "_" . uniqid() . "." . $ext;

        if (!move_uploaded_file($countryImage['tmp_name'], $upload_path . $fileName)) {
            sendResponse(400, "File uploading error");
        }
    }

    // INSERT (image can be NULL)
    $stmt = $conn->prepare(
        "INSERT INTO countries (country_name, country_icon, country_currency, country_code)
         VALUES (?, ?, ?, ?)"
    );

    $stmt->execute([$countryName, $fileName, $countryCurrency, $countryCode]);
    sendResponse(200, "Country added successfully");

} catch (PDOException $e) {
    sendResponse(500, "Server Error");
}
