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

        try {
            $stripe = new \Stripe\StripeClient($_SETTINGS["stripe_sk"]);
            $stripe->paymentIntents->update($intent->id, ["metadata" => ["tracking_number" => "$shipment->tracking_code", "rate" => $price - 1.00]]);
        } catch (Exception $exx) {

        }

        $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);

            // Add restricted delivery "stamp"
            if ($shipment->options->delivery_confirmation == "SIGNATURE_RESTRICTED") {
                $restrictedstamp = imagecreatefrompng(__DIR__ . "/restricted_delivery.png");
                imagecopyresampled($paperimage, $restrictedstamp, 300, 1400, 0, 0, 600, 225, 600, 225);
            }
        } 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();

        if (!empty($shipment->from_address->email)) {
            try {
                $mail = new Email();
                $emailsettings = $_SETTINGS["email"];
                $mail->setSMTP($emailsettings["server"], $emailsettings["port"], true, $emailsettings["user"], $emailsettings["password"], $emailsettings["security"]);
                $mail->setFrom($emailsettings["user"], "CertifiedFromHome.com");
                $mail->addTo($shipment->from_address->email);
                $mail->setSubject("Your CertifiedFromHome Receipt");
                $body = "Thanks for using CertifiedFromHome.com!\r\nYour card has been charged a total of $" . number_format($price, 2) . ".\r\n";
                if (!empty($shipment->options->certified_mail)) {
                    $body .= "You can track your letter with this tracking code: " . $shipment->tracking_code . "\r\n";
                    $body .= "Or click here: https://tools.usps.com/go/TrackConfirmAction?qtc_tLabels1=" . $shipment->tracking_code . "\r\n\r\n";
                }
                if (!empty($shipment->options->return_receipt)) {
                    $body .= "You purchased an electronic return receipt. To request one, go to the link above, "
                            . "make sure the tracking says \"Delivered\", "
                            . "scroll down and click on \"Return Receipt Electronic\", and fill in the form. USPS will "
                            . "email you a PDF proof of delivery with the recipient's signature and other info.\r\n\r\n";
                }
                $body .= "Here's a link to your purchased postage, just in case: https://certifiedfromhome.com/pdf/" . $pdffile
                        . "\r\nPlease note that while you can print it more than once, mailing multiple copies is illegal.\r\n";
                $body .= "If you need any help, just reply to this email. Thanks again!";
                $mail->setBody($body);
                $mail->send();
            } catch (Exception $ex) {

            }
        }

        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()]));
}