<?php
declare(strict_types=1);

namespace App\Modules\Sales\Services;

use App\Core\App;

final class CustomerPricingService
{
    public static function getPrice(int $itemId, ?int $memberId = null): ?string
    {
        if (!$memberId) return null;

        $db = App::getInstance()->db();

        $customPrice = $db->selectOne(
            "SELECT cip.price
             FROM customer_item_prices cip
             JOIN customer_price_lists cpl ON cpl.id = cip.price_list_id
             WHERE cip.item_id = ? AND cpl.member_id = ? AND cpl.is_active = 1
             ORDER BY cip.id DESC LIMIT 1",
            [$itemId, $memberId]
        );

        return $customPrice ? (string) $customPrice['price'] : null;
    }

    public static function getPriceList(int $memberId): array
    {
        $db = App::getInstance()->db();

        $list = $db->selectOne(
            "SELECT * FROM customer_price_lists WHERE member_id = ? AND is_active = 1 ORDER BY id DESC LIMIT 1",
            [$memberId]
        );

        if (!$list) return [];

        return $db->select(
            "SELECT cip.*, i.name_ar, i.selling_price as default_price
             FROM customer_item_prices cip
             JOIN inventory_items i ON i.id = cip.item_id
             WHERE cip.price_list_id = ?
             ORDER BY i.name_ar",
            [(int) $list['id']]
        );
    }

    public static function savePriceList(int $memberId, array $items, ?string $notes = null): int
    {
        $db = App::getInstance()->db();
        $employee = App::getInstance()->currentEmployee();

        $db->query("UPDATE customer_price_lists SET is_active = 0 WHERE member_id = ?", [$memberId]);

        $listId = $db->insert('customer_price_lists', [
            'member_id' => $memberId,
            'name_ar' => 'قائمة أسعار خاصة',
            'discount_type' => 'fixed_price',
            'notes' => $notes,
            'is_active' => 1,
            'created_by' => $employee ? (int) $employee->id : null,
            'created_at' => date('Y-m-d H:i:s'),
        ]);

        foreach ($items as $item) {
            $db->insert('customer_item_prices', [
                'price_list_id' => $listId,
                'item_id' => (int) $item['item_id'],
                'price' => (string) $item['price'],
                'min_quantity' => $item['min_quantity'] ?? '1.000',
            ]);
        }

        return $listId;
    }
}
