<?php

require_once __DIR__ . "/required.php";

$shipmentinfo = [];

try {

    $shipment = \EasyPost\Shipment::retrieve($_REQUEST["shipmentid"]);

    $price = 0;
    foreach ($shipment->rates as $rate) {
        if ($rate->id == $_REQUEST["rateid"]) {
            $retail_rate = $rate->retail_rate ?? ($rate->list_rate ?? $rate->rate);
            $price = $retail_rate + 1.00;
        }
    }

    if ($price == 0) {
        throw new Exception("Invalid rate selection. Refresh the page and try again. Your card was not charged.");
    }

    if ($price != $_REQUEST["price"]) {
        throw new Exception("Price mismatch detected. Refresh the page and try again. Your card was not charged.");
    }

    // make the payment intent but don't capture it yet, in case something goes wrong.
    $intent = \Stripe\PaymentIntent::create([
                'amount' => $price * 100,
                'currency' => 'usd',
                'payment_method' => $_REQUEST["stripeid"],
                'description' => "CertifiedFromHome.com",
                'statement_descriptor' => "CrtfdFrmHome",
                'payment_method_types' => ['card'],
                'capture_method' => 'manual',
                'confirm' => true
    ]);

    if ($intent->status == 'requires_capture') {
        // Payment will go through, proceed to spend money on postage

        if (empty($shipment->postage_label)) {
            // Do this conditionally in case label got purchased but payment somehow failed,
            // allowing a retry of the payment.
            $shipment->buy(['rate' => ['id' => $_REQUEST["rateid"]]]);
        }

        $labelurl = $shipment->postage_label->label_url;

        // load postage image
        $labelimage = imagecreatefrompng($labelurl);

        if (!empty($shipment->options->certified_mail)) {
            // load page template
            $paperimage = imagecreatefrompng(__DIR__ . "/papertemplate.png");

            // copy postage label image into page template
            imagecopyresampled($paperimage, $labelimage, 225, 750, 0, 0, 2100, 900, 2100, 900);
        } else {
            // load page template
            $paperimage = imagecreatefrompng(__DIR__ . "/papertemplate_notracking.png");

            // copy postage label image into page template
            imagecopyresampled($paperimage, $labelimage, 225, 600, 0, 0, 2100, 900, 2100, 900);
        }

        // save generated image to temp file
        $tmpfile = tempnam(sys_get_temp_dir(), "certifiedlabel");
        imagepng($paperimage, $tmpfile);

        // Generate PDF from image
        $pdf = new FPDF('P', 'in', 'Letter');
        $pdf->AddPage();
        $pdf->Image($tmpfile, 0, 0, -300, -300, "PNG");

        $pdffile = date("Ymd") . "_" . hash("sha256", $_REQUEST["shipmentid"]) . ".pdf";
        $pdf->Output("F", __DIR__ . "/pdf/" . $pdffile);

        // cleanup temp file
        unlink($tmpfile);

        // get paid
        $intent->capture();

        header("Content-Type: application/json");
        exit(json_encode([
            "status" => "OK",
            "pdf" => "https://certifiedfromhome.com/pdf/" . $pdffile,
            "trackingcode" => $shipment->tracking_code
        ]));
    } else {
        throw new Exception("Payment didn't go through. Please try again or try a different card.");
    }
} catch (Exception $ex) {
    header("Content-Type: application/json");
    exit(json_encode(["status" => "ERROR", "message" => $ex->getMessage()]));
}