<?php
/** Template Name: Woocommerce Cart Template */
get_header();

/** ----------------------------------------------------------------------------
 * INITIAL CHECK FROM EMPTY CART
 * If there isn't anything in the cart, then we have way less to do
 * -----------------------------------------------------------------------------
 */
$allItems = WC()->cart->get_cart();
if (!is_array($allItems) || count($allItems) == 0) {
    $pageToRedirectTo = site()->getPost(get_field('bad_woocommerce_page_redirect', 'options'), ["permalink"]);

    echo site()->render("empty_cart", [
        "headline" => get_field("empty_cart_headline", "options"),
        "content" => get_field("empty_cart_content", "options"),
        "product-page-url" => $pageToRedirectTo["permalink"],
    ]);
    get_footer();
    exit(); // stop processing early
}

/** ----------------------------------------------------------------------------
 * FIRST THINGS FIRST
 * There can only be one item in the cart at a time, so let's set the activation
 * fee to the session. Looping over all products in the cart should get us what
 * we want, even if it's unintuitive. Thanks WooCommerce.
 * -----------------------------------------------------------------------------
 */
$item = null;
foreach ($allItems as $i) {
    $item = $i;
}
$_SESSION["Activation Fee"] = get_field("activation_fee", $item["product_id"]);


/** ----------------------------------------------------------------------------
 * NEXT UP - ADD ONS
 * Not all products should show all add ons. No add ons are required, and each
 * add on can only be added to the "cart" once, so we will treat these like fees
 * to keep things as simple as possible.
 * -----------------------------------------------------------------------------
 *  First, let's check all add ons to see if each one should be displayed
 *  depending on the current cart item.
 */
$availableAddOns = array_filter(get_field("add_ons", "options"), function ($addOn) use ($item) {
    return in_array($item["product_id"], $addOn["available_for_products"]);
});

$AddOnsOnetime = array_filter(get_field("one_time_add_ons", "options"), function ($addOn) use ($item) {
    return in_array($item["product_id"], $addOn["available_for_products"]);
});

if (isset($_GET["add-on"])) {
    $addon = $_GET["add-on"];
    if (stripos($addon, "Professional Install") !== false) {
        if (isset($_SESSION["one-time"])) {
            unset($_SESSION["one-time"]);
        } else {
            foreach ($AddOnsOnetime as $ao) {
                if ($_GET["add-on"] == $ao["label"]) {
                    $_SESSION["one-time"][$_GET["add-on"]] = $ao;
                    break;
                }
            }
        }
    }
}

if (isset($_GET["add-on"])) {
    $add_on_modified = false;

    if (isset($_SESSION["addOns"][$_GET["add-on"]])) {
        unset($_SESSION["addOns"][$_GET["add-on"]]);
        $add_on_modified = true;
    } else {
        foreach ($availableAddOns as $ao) {
            if ($_GET["add-on"] == $ao["label"]) {
                $_SESSION["addOns"][$_GET["add-on"]] = $ao;
                $add_on_modified = true;
                break;
            }
        }
    }

    if ($add_on_modified) {
        $redirect_url = remove_query_arg('add-on', wc_get_cart_url());
        wp_redirect($redirect_url);
        exit();
    }
}

foreach ($availableAddOns as $key => $addOn) {
    $availableAddOns[$key]["in_cart"] = isset($_SESSION["addOns"][$addOn["label"]]);
}

foreach ($AddOnsOnetime as $mykey => $oneTime) {
    $AddOnsOnetime[$mykey]["in_cart"] = isset($_SESSION["one-time"]);
}


$cart = WC()->cart;
$cart_contents = $cart->get_cart();

foreach ($cart_contents as $cart_item_key => $cart_item):
endforeach;


$attributeRatePlan = $cart_item['variation']['attribute_rate-plan'];
$keylb = $_SESSION["addOns"]["Key Lockbox"]['label'];

if ($attributeRatePlan === 'Annually') {

foreach ($availableAddOns as &$addOn) {
    if ($addOn["label"] === "Key Lockbox") {
        $addOn["price"] = "0.00";
    }
    }
}

$addOnOutput = site()->view("add_on_chooser", [
    "add-ons" => $availableAddOns,
    "add-ons-onetime" => $AddOnsOnetime,
]);


// this function is defined in functions.php as we use it in a few places
$cartSummary = generateCartSummary();

// Check if the form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['apply_coupon'])) {
    $coupon_code = isset($_POST['coupon_code']) ? wc_format_coupon_code($_POST['coupon_code']) : '';

    if (!empty($coupon_code)) {
        WC()->cart->apply_coupon($coupon_code);
        wc_add_notice(__('Coupon applied successfully.', 'woocommerce'));
        // Redirect to prevent form resubmission on page reload
        wp_redirect(wc_get_cart_url());
        exit;
    } else {
        wc_add_notice(__('Please enter a valid coupon code.', 'woocommerce'), 'error');
    }
}
echo site()->view("cart", [
    "installation" => $installationOutput,
    "addOns" => $addOnOutput,
    "content" => $cartSummary,
    "couponSummary" => $couponSummary,
]);

get_footer();
