<?php
namespace App\Core;

class ShippingEngine {
    public static function quote(float $subtotal,float $weight=1,?int $districtId=null,?int $areaId=null,?int $vendorId=null,?int $productId=null): array {
        $charge=120.00;
        $params=[$districtId,$areaId,$vendorId,$productId,$subtotal];
        $rule=Database::safeFetchOne(
            'SELECT * FROM shipping_rules WHERE status="active"
             AND (district_id IS NULL OR district_id=?)
             AND (area_id IS NULL OR area_id=?)
             AND (vendor_id IS NULL OR vendor_id=?)
             AND (product_id IS NULL OR product_id=?)
             AND (is_free=0 OR COALESCE(min_order_amount,0)<=?)
             ORDER BY (area_id IS NOT NULL) DESC,(district_id IS NOT NULL) DESC,(product_id IS NOT NULL) DESC,(vendor_id IS NOT NULL) DESC,is_free DESC,id DESC LIMIT 1',
            $params
        );
        if($rule)$charge=(int)($rule['is_free']??0)===1?0.0:(float)($rule['charge']??$charge);
        if(!$rule){
            $zone=Database::safeFetchOne('SELECT * FROM delivery_zones WHERE status="active" AND (district_ids="" OR FIND_IN_SET(?,district_ids)) AND (area_ids="" OR FIND_IN_SET(?,area_ids)) ORDER BY (area_ids<>"") DESC,id ASC LIMIT 1',[$districtId,$areaId]);
            if($zone){$charge=$subtotal>=(float)($zone['free_delivery_min']??PHP_FLOAT_MAX)?0.0:(float)($zone['base_charge']??$charge);$charge+=max(0,$weight-1)*(float)($zone['extra_kg_charge']??0);}
        }
        return ['subtotal'=>$subtotal,'shipping_charge'=>round(max(0,$charge),2),'total'=>round($subtotal+max(0,$charge),2),'district_id'=>$districtId,'area_id'=>$areaId];
    }
}
