<?php

require_once __DIR__ . "/required.php";

$shipmentinfo = [];

try {

    if (empty($_REQUEST["to_street"])) {
        throw new Exception("Please enter the delivery address.");
    }

    if (empty($_REQUEST["to_name"]) && empty($_REQUEST["to_company"])) {
        throw new Exception("Please enter the recipient's name and/or a company name.");
    }

    if (empty($_REQUEST["to_zip"]) && (empty($_REQUEST["to_city"]) || empty($_REQUEST["to_state"]))) {
        throw new Exception("Please enter the delivery ZIP code, or if you don't know, enter the city and state and we'll find the ZIP code for you.");
    }

    if (empty($_REQUEST["from_name"]) || empty($_REQUEST["from_street"])) {
        throw new Exception("Please enter your return address.");
    }

    if (empty($_REQUEST["from_zip"]) && (empty($_REQUEST["from_city"]) || empty($_REQUEST["from_state"]))) {
        throw new Exception("Please enter your ZIP code, or if you don't know, enter your city and state and we'll find the ZIP code for you.");
    }

    $shipmentinfo["from_address"] = \EasyPost\Address::create([
                "verify" => array("delivery"),
                "name" => $_REQUEST["from_name"],
                "street1" => $_REQUEST["from_street"],
                "street2" => $_REQUEST["from_street2"],
                "city" => $_REQUEST["from_city"],
                "state" => $_REQUEST["from_state"],
                "zip" => $_REQUEST["from_zip"],
                "country" => "US"
    ]);

    $shipmentinfo["to_address"] = \EasyPost\Address::create([
                "verify" => array("delivery"),
                "name" => $_REQUEST["to_name"],
                "company" => $_REQUEST["to_company"],
                "street1" => $_REQUEST["to_street"],
                "street2" => $_REQUEST["to_street2"],
                "city" => $_REQUEST["to_city"],
                "state" => $_REQUEST["to_state"],
                "zip" => $_REQUEST["to_zip"],
                "country" => "US"
    ]);

    $shipmentinfo["parcel"] = \EasyPost\Parcel::create([
                "predefined_package" => "Letter",
                "weight" => 3.5
    ]);

    if ($_REQUEST["postagetype"] == "certified") {
        $shipmentinfo["options"]["certified_mail"] = true;
    } else if ($_REQUEST["postagetype"] == "certified_receipt") {
        $shipmentinfo["options"]["certified_mail"] = true;
        $shipmentinfo["options"]["return_receipt"] = true;
    }

    $shipmentinfo["options"]["label_format"] = "PNG";
    $shipmentinfo["options"]["label_size"] = "7x3";

    $shipmentinfo["options"]["label_date"] = date("c", strtotime("tomorrow"));

    $shipment = \EasyPost\Shipment::create($shipmentinfo);

    $selectedrate = [];
    for ($i = 0; $i < count($shipment->rates); $i++) {
        $rate = $shipment->rates[$i];

        $retail_rate = $rate->retail_rate ?? ($rate->list_rate ?? $rate->rate);
        if ($rate->service != "First") {
            continue;
        }

        $selectedrate = [
            "id" => $rate->id,
            "cost" => $retail_rate,
            "price" => $retail_rate + 1.00
        ];
    }

    if (empty($selectedrate)) {
        throw new Exception("Unable to find price. Check your destination address and try again.");
    }

    $address = $shipment->to_address;
    $fromaddress = $shipment->from_address;

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

    exit(json_encode([
        "status" => "OK",
        "rate" => $selectedrate,
        "shipmentid" => $shipment->id,
        "address" => [
            "name" => $address->name ?? "",
            "company" => $address->company ?? "",
            "street1" => $address->street1 ?? "",
            "street2" => $address->street2 ?? "",
            "city" => $address->city ?? "",
            "state" => $address->state ?? "",
            "zip" => $address->zip ?? ""
        ],
        "fromaddress" => [
            "name" => $fromaddress->name ?? "",
            "street1" => $fromaddress->street1 ?? "",
            "street2" => $fromaddress->street2 ?? "",
            "city" => $fromaddress->city ?? "",
            "state" => $fromaddress->state ?? "",
            "zip" => $fromaddress->zip ?? ""
        ]]
    ));
} catch (Exception $ex) {
    header("Content-Type: application/json");
    exit(json_encode(["status" => "ERROR", "message" => $ex->getMessage()]));
}