<?php
declare(strict_types=1);

namespace Instinctor\Services;

use Instinctor\Core\Config;
use Instinctor\Core\DB;


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

/**
 * ProductBundleService - Product bundles, build-your-own, bundle discounts
 * @since 2.0.44
 */
class ProductBundleService
{
    /**
     * Check if addon is active
     */
    public static function isActive(): bool
    {
        return true;
    }
    
    /**
     * Get all bundles
     */
    public static function getBundles(): array
    {
        $table = DB::prefix() . 'instinctor_product_bundles';
        
        if (DB::get_var("SHOW TABLES LIKE '{$table}'") !== $table) {
            return [];
        }
        
        return DB::get_results("SELECT * FROM {$table} ORDER BY created_at DESC", ARRAY_A) ?: [];
    }
    
    /**
     * Get bundle by ID
     */
    public static function getBundle(int $id): ?array
    {
        $table = DB::prefix() . 'instinctor_product_bundles';
        
        $bundle = DB::get_row(
            DB::prepare("SELECT * FROM {$table} WHERE id = %d", $id), // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Safe table name
            ARRAY_A
        );
        
        if ($bundle) {
            $bundle['products'] = json_decode($bundle['products'] ?? '[]', true);
        }
        
        return $bundle ?: null;
    }
    
    /**
     * Save bundle
     */
    public static function saveBundle(array $data): int
    {
        $table = DB::prefix() . 'instinctor_product_bundles';
        
        $bundleData = [
            'name' => sanitize_text_field($data['name'] ?? ''),
            'description' => sanitize_textarea_field($data['description'] ?? ''),
            'products' => wp_json_encode($data['products'] ?? []),
            'bundle_type' => sanitize_text_field($data['bundle_type'] ?? 'fixed'),
            'discount_type' => sanitize_text_field($data['discount_type'] ?? 'percent'),
            'discount_value' => floatval($data['discount_value'] ?? 0),
            'min_products' => intval($data['min_products'] ?? 0),
            'max_products' => intval($data['max_products'] ?? 0),
            'is_active' => intval($data['is_active'] ?? 1),
        ];
        
        if (!empty($data['id'])) {
            $bundleData['updated_at'] = current_time('mysql');

            DB::update($table, $bundleData, ['id' => intval($data['id'])]);
            return intval($data['id']);
        } else {
            $bundleData['created_at'] = current_time('mysql');
            DB::insert($table, $bundleData);
            return DB::insert_id();
        }
    }
    
    /**
     * Delete bundle
     */
    public static function deleteBundle(int $id): bool
    {
        $table = DB::prefix() . 'instinctor_product_bundles';
        return DB::delete($table, ['id' => $id]) !== false;
    }
    
    /**
     * Calculate bundle price
     */
    public static function calculateBundlePrice(int $bundleId, array $selectedProducts = []): array
    {
        $bundle = self::getBundle($bundleId);
        
        if (!$bundle) {
            return ['original' => 0, 'discounted' => 0, 'savings' => 0];
        }
        
        $productTable = DB::prefix() . 'instinctor_products';
        
        $productIds = $bundle['bundle_type'] === 'fixed' ? $bundle['products'] : $selectedProducts;
        
        if (empty($productIds)) {
            return ['original' => 0, 'discounted' => 0, 'savings' => 0];
        }
        
        $placeholders = implode(',', array_fill(0, count($productIds), '%d'));
        $prices = DB::get_col(
            DB::prepare(
                "SELECT price FROM {$productTable} WHERE id IN ({$placeholders})", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- Dynamic IN clause, safe table
                ...$productIds
            )
        );
        
        $originalTotal = array_sum($prices);
        
        if ($bundle['discount_type'] === 'percent') {
            $discount = $originalTotal * ($bundle['discount_value'] / 100);
        } else {
            $discount = $bundle['discount_value'];
        }
        
        $discountedTotal = max(0, $originalTotal - $discount);
        
        return [
            'original' => round($originalTotal, 2),
            'discounted' => round($discountedTotal, 2),
            'savings' => round($discount, 2),
        ];
    }
    
    /**
     * Create database tables
     */
    public static function createTables(): void
    {
        $charset = DB::get_charset_collate();
        
        $table = DB::prefix() . 'instinctor_product_bundles';
        
        $sql = "CREATE TABLE IF NOT EXISTS {$table} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            name varchar(255) NOT NULL,
            description text,
            products longtext,
            bundle_type varchar(20) DEFAULT 'fixed',
            discount_type varchar(20) DEFAULT 'percent',
            discount_value decimal(10,2) DEFAULT 0,
            min_products int DEFAULT 0,
            max_products int DEFAULT 0,
            is_active tinyint(1) DEFAULT 1,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            updated_at datetime DEFAULT NULL,
            PRIMARY KEY (id)
        ) {$charset};";
        
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
    }
}
