<?php

require_once __DIR__ . "/required.php";

$shipmentinfo = [];

try {

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

    $price = 0;
    $cost = 0;
    foreach ($shipment->rates as $rate) {
        if ($rate->id == $_REQUEST["rateid"]) {
            $cost = $rate->rate;
            $retail_rate = $rate->retail_rate ?? ($rate->list_rate ?? $rate->rate);
            if ($retail_rate - $cost > 3) {
                // Cap at $3 profit to be nice
                $price = $cost + 3.00;
            } else {
                $price = $cost + 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', 'link'],
        '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"]]]);
        }

        $pdffile = date("Ymd") . "_" . hash("sha256", $shipment->id) . ".pdf";

        try {
            $stripe = new \Stripe\StripeClient($_SETTINGS["stripe_sk"]);
            $stripe->paymentIntents->update($intent->id, [
                "metadata" => [
                    "tracking_number" => "$shipment->tracking_code",
                    "from_email" => (empty($shipment->from_address->email) ? "None" : $shipment->from_address->email . ""),
                    "rate" => number_format($cost, 2),
                    "label" => $pdffile
                ],
                "amount_details" => [
                    "line_items" => [
                        [
                            "product_name" => "Shipping Label",
                            "quantity" => 1,
                            "unit_cost" => $price * 100,
                            "unit_of_measure" => "each",
                            "product_code" => "CRTFIEDMAIL",
                            "tax" => [
                                "total_tax_amount" => 0
                            ],
                            "payment_method_options" => [
                                "card" => [
                                    "commodity_code" => "43231515" // UNSPSC: Mailing and shipping software / Software that offices can use as an alternative to postage meters to print postage stamps and shipping labels.
                                ]
                            ]
                        ]
                    ]
                ],
                "payment_details" => [
                    "order_reference" => "$shipment->tracking_code"
                ]
            ]);
        } catch (Exception $exx) {

        }

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

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

        $paperSize = "Letter";
        $paperOrientation = "P";
        if (!empty($_REQUEST["no10_envelope"]) && $_REQUEST["no10_envelope"] == "1") {
            $paperSize = [9.5, 4.125];
            $paperOrientation = "L";
            if ($shipment->postage_label->label_size == "4x6") {
                if (!empty($shipment->options->certified_mail)) {
                    // envelope with banner
                    $paperimage = imagecreatefrompng(__DIR__ . "/papertemplate_no10_4x6_certified.png");
                } else {
                    // plain envelope
                    $paperimage = imagecreatefrompng(__DIR__ . "/papertemplate_no10.png");
                }
                $labelimage = imagerotate($labelimage, 270, 0);
                imagecopyresampled($paperimage, $labelimage, 525, 19, 0, 0, 1200, 1800, 1200, 1800);
            } else {
                if (!empty($shipment->options->certified_mail)) {
                    // envelope with banner
                    $paperimage = imagecreatefrompng(__DIR__ . "/papertemplate_no10_certified.png");
                    imagecopyresampled($paperimage, $labelimage, 375, 190, 0, 0, 2100, 900, 2100, 900);
                    if ($shipment->options->delivery_confirmation == "SIGNATURE_RESTRICTED") {
                        $restrictedstamp = imagecreatefrompng(__DIR__ . "/restricted_delivery.png");
                        imagecopyresampled($paperimage, $restrictedstamp, 450, 825, 0, 0, 600, 225, 600, 225);
                    }
                } else {
                    // plain envelope
                    $paperimage = imagecreatefrompng(__DIR__ . "/papertemplate_no10.png");
                    imagecopyresampled($paperimage, $labelimage, 375, 90, 0, 0, 2100, 900, 2100, 900);
                }
            }
        } else if ($shipment->postage_label->label_size == "4x6") {
            if ((!empty($_REQUEST["label_only"]) && $_REQUEST["label_only"] == "1") || $shipment->parcel->predefined_package == "FlatRateEnvelope") {
                if (!empty($shipment->options->certified_mail)) {
                    // label and banner only
                    $paperimage = imagecreatefrompng(__DIR__ . "/papertemplate-labelonly-certified.png");
                } else {
                    // label only
                    $paperimage = imagecreatefrompng(__DIR__ . "/papertemplate-labelonly.png");
                }
                imagecopyresampled($paperimage, $labelimage, 675, 753, 0, 0, 1200, 1800, 1200, 1800);
            } else {
                if (!empty($shipment->options->certified_mail)) {
                    // envelope with banner
                    $paperimage = imagecreatefrompng(__DIR__ . "/papertemplate.png");
                } else {
                    // plain envelope
                    $paperimage = imagecreatefrompng(__DIR__ . "/papertemplate_notracking.png");
                }
                $labelimage = imagerotate($labelimage, 270, 0);
                imagecopyresampled($paperimage, $labelimage, 375, 750, 0, 0, 1800, 1200, 1800, 1200);
                if ($shipment->options->delivery_confirmation == "SIGNATURE_RESTRICTED") {
                    $restrictedstamp = imagecreatefrompng(__DIR__ . "/restricted_delivery.png");
                    $restrictedstamp = imagerotate($restrictedstamp, 270, 0);
                    imagecopyresampled($paperimage, $restrictedstamp, 2200, 1050, 0, 0, 225, 600, 225, 600);
                    imagecopyresampled($paperimage, $restrictedstamp, 130, 1050, 0, 0, 225, 600, 225, 600);
                }
            }
        } else 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($paperOrientation, 'in', $paperSize);
        $pdf->AddPage();
        $pdf->Image($tmpfile, 0, 0, -300, -300, "PNG");

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