<?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");
        exit;
    }

    $id = $_POST['id'] ?? null;
    $countryName = $_POST['name'] ?? null;
    $countryImage = $_FILES['country_image'] ?? null;
    $countryCurrency = $_POST['currency'] ?? null;
    $countryCode = $_POST['code'] ?? null;


    if (!$id) {
        sendResponse(400, "id is required");
        exit;
    }

    if (!$countryName && !$countryImage && !$countryCode && !$countryCurrency) {
        sendResponse(400, "name or icon or code or currency is required");
        exit;
    }


    $stmt = $conn->prepare(
        "SELECT country_icon FROM countries WHERE id = ?"
    );
    $stmt->execute([$id]);
    $country = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$country) {
        sendResponse(404, "Country not found");
        exit;
    }


    $fileName = $country['country_icon'];


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

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

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

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

        $upload_path = dirname(__DIR__, 2) . "/uploads/country_icon/";


        if (!is_dir($upload_path)) {
            mkdir($upload_path, 0777, true);
        }

        $newFileName = time() . "_" . uniqid() . "." . $ext;

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

        // delete old icon
        if ($fileName && file_exists($upload_path . $fileName)) {
            unlink($upload_path . $fileName);
        }

        $fileName = $newFileName;
    }

    if ($countryName !== null) {

        $stmt = $conn->prepare(
            "UPDATE countries SET country_name = ?, country_icon = ?, country_currency = ?, country_code = ? WHERE id = ? AND deleted_at IS NULL"
        );
        $stmt->execute([$countryName, $fileName, $countryCurrency, $countryCode, $id]);
    } else {
        $stmt = $conn->prepare(
            "UPDATE countries SET country_icon = ? WHERE id = ?"
        );
        $stmt->execute([$fileName, $id]);
    }
    sendResponse(200, "Country updated successfully");
    exit;

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