<?php
if (!defined('ABSPATH')) exit;

/** Woo shipping method that quotes postage from RecordGod (record-count → AusPost flat rate). */
class RG_Shipping extends WC_Shipping_Method {

    function __construct($instance_id = 0) {
        $this->id = 'recordgod';
        $this->instance_id = absint($instance_id);
        $this->method_title = 'RecordGod Postage';
        $this->method_description = 'Live AusPost flat-rate quote from RecordGod (Parcel / Express Post).';
        $this->supports = ['shipping-zones', 'instance-settings', 'settings'];
        $this->init();
    }

    function init() {
        $this->init_form_fields();
        $this->init_settings();
        $this->enabled = $this->get_option('enabled', 'yes');
        $this->title = $this->get_option('title', 'Postage');
        add_action('woocommerce_update_options_shipping_' . $this->id, [$this, 'process_admin_options']);
    }

    function init_form_fields() {
        $this->instance_form_fields = [
            'enabled' => ['title' => 'Enable', 'type' => 'checkbox', 'default' => 'yes'],
            'title'   => ['title' => 'Title', 'type' => 'text', 'default' => 'Postage'],
        ];
    }

    function calculate_shipping($package = []) {
        $units = 0;
        foreach ($package['contents'] as $line) $units += (int) $line['quantity'];
        if ($units < 1) return;

        $q = RG_API::get('/shop/shipping/quote', ['units' => $units], 30);
        if (!$q || empty($q['options'])) return;

        foreach ($q['options'] as $opt) {
            $this->add_rate([
                'id'    => $this->id . ':' . $opt['service'],
                'label' => $opt['label'],
                'cost'  => (float) $opt['price'],
                'calc_tax' => 'per_order',
            ]);
        }
    }
}
