<?php
/*
 * Copyright (c) 2026 AltumCode (https://altumcode.com/)
 *
 * This software is licensed exclusively by AltumCode and is sold only via https://altumcode.com/.
 * Unauthorized distribution, modification, or use of this software without a valid license is not permitted and may be subject to applicable legal actions.
 *
 * 🌍 View all other existing AltumCode projects via https://altumcode.com/
 * 📧 Get in touch for support or general queries via https://altumcode.com/contact
 * 📤 Download the latest version via https://altumcode.com/downloads
 *
 * 🐦 X/Twitter: https://x.com/AltumCode
 * 📘 Facebook: https://facebook.com/altumcode
 * 📸 Instagram: https://instagram.com/altumcode
 */

namespace Altum\Controllers;


use Altum\Title;

defined('ALTUMCODE') || die();

class StoreInvoice extends Controller {

    public function index() {

        $order_id = isset($this->params[0]) ? (int) $this->params[0] : null;
        $hash = $_GET['hash'] ?? null;


        /* Get details about the order */
        if(!$order = db()->where('order_id', $order_id)->getOne('orders')) {
            throw_404();
        }

        if(!in_array($order->processor, ['stripe', 'paypal', 'mollie', 'paystack'])) {
            throw_404();
        }

        $payment_hash = md5($order->order_id . $order->order_number . $order->datetime);

        if((is_logged_in() && $order->user_id != $this->user->user_id) && $hash != $payment_hash) {
            throw_404();
        }

        /* Make sure a payment exists */
        if(!$payment = db()->where('order_id', $order->order_id)->getOne('customers_payments')) {
            throw_404();
        }

        /* Get details about the store */
        if(!$store = db()->where('store_id', $order->store_id)->getOne('stores')) {
            throw_404();
        }

        /* Try to see if we get details from the billing */
        $store->business = json_decode($store->business);
        $payment->billing = json_decode($payment->billing);

        /* Set a custom title */
        Title::set(sprintf(l('invoice.title'), $store->business->invoice_nr_prefix . $payment->customer_payment_id));

        /* Prepare the view */
        $data = [
            'payment' => $payment,
            'order' => $order,
            'store' => $store,
        ];

        $view = new \Altum\View('store-invoice/index', (array) $this);

        $this->add_view_content('content', $view->run($data));

    }


}
