<?php

if (!defined('ABSPATH')) { exit; }

class AIEO_MOI_Voucher_Store {

    
    public static function save($vendor_slug, $remote_order_id, $base64_content, $format = 'pdf') {
        $upload = wp_upload_dir();
        if (!empty($upload['error'])) { return ''; }

        $ext = self::sanitise_extension($format);
        $vendor_slug = sanitize_key((string) $vendor_slug);
        $remote_id   = preg_replace('/[^A-Za-z0-9_-]/', '_', (string) $remote_order_id);
        if ($vendor_slug === '' || $remote_id === '') { return ''; }

        $rel_dir = 'aieo-moi/vouchers/' . $vendor_slug;
        $abs_dir = trailingslashit($upload['basedir']) . $rel_dir;
        if (!file_exists($abs_dir)) {
            wp_mkdir_p($abs_dir);
            
            
            $idx = $abs_dir . '/index.html';
            if (!file_exists($idx)) { @file_put_contents($idx, ''); }
        }

        $abs_path = trailingslashit($abs_dir) . $remote_id . '.' . $ext;
        $bytes = base64_decode($base64_content, true);
        if ($bytes === false || $bytes === '') { return ''; }
        if (file_put_contents($abs_path, $bytes) === false) { return ''; }

        return trailingslashit($upload['baseurl']) . $rel_dir . '/' . $remote_id . '.' . $ext;
    }

    private static function sanitise_extension($format) {
        $f = strtolower((string) $format);
        return in_array($f, array('pdf','png','jpg','jpeg','zpl'), true) ? $f : 'pdf';
    }
}
