<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Merchant extends Model
{
    protected $guarded = [];

    // STATUSES
    const STATUS_DRAFT = 0;

    const STATUS_ACTIVE = 1;

    const STATUS_SUSPENDED = 2;

    const FEATURED_TRUE = 1;

    const FEATURED_FALSE = 0;

    const TYPE_PHARMACY = 'pharmacie';

    const TYPE_DEPOT_PHARMACEUTIQUE = 'depot-pharmaceutique';

    const MERCHANT_TYPES = [
        ['id' => 'pharmacie', 'name' => 'Pharmacie', 'slug' => 'pharmacie', 'color' => 'blue'],
        ['id' => 'depot-pharmaceutique', 'name' => 'Depôt pharmaceutique', 'slug' => 'depot-pharmaceutique', 'color' => 'green'],
    ];

    const MERCHANT_STATUSES = [
        ['id' => self::STATUS_DRAFT, 'slug' => 'draft', 'name' => 'En attente', 'color' => 'yellow'],
        ['id' => self::STATUS_ACTIVE, 'slug' => 'active', 'name' => 'Actif', 'color' => 'green'],
        ['id' => self::STATUS_SUSPENDED, 'slug' => 'suspended', 'name' => 'Suspendu', 'color' => 'red'],
    ];

    public function getRouteKeyName()
    {
        return 'slug';
    }

    public function products()
    {
        return $this->hasMany(Product::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function contact()
    {
        return $this->belongsTo(Contact::class);
    }

    public function address()
    {
        return $this->belongsTo(Address::class);
    }

    public function sales()
    {
        return $this->hasMany(Sale::class);
    }

    public function orders()
    {
        return $this->hasMany(Order::class);
    }

    public function purchaseOrders()
    {
        return $this->hasMany(PurchaseOrder::class);
    }

    public function locations()
    {
        return $this->hasMany(Location::class);
    }

    public function categories()
    {
        return $this->hasMany(Category::class);
    }

    public function stockEntries()
    {
        return $this->hasMany(StockEntry::class);
    }

    public function expenseCategories()
    {
        return $this->hasMany(ExpenseCategory::class);
    }

    public function expenses()
    {
        return $this->hasMany(Expense::class);
    }

    public static function generateSlug($name)
    {
        $baseSlug = Str::slug($name);
        $slug = $baseSlug;
        $counter = 0;

        while (self::where('slug', $slug)->exists()) {
            $slug = "{$baseSlug}-{$counter}";
            $counter++;
        }

        return $slug;
    }

    public static function generateMerchantCode()
    {
        $year = now()->format('y'); // 2 digits (24 for 2024)
        $month = now()->format('m'); // 2 digits (01-12)
        $day = now()->format('d'); // 2 digits (01-31)
        $random = str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT); // 4 random digits
        $random2 = str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT); // 4 random digits
        $timestamp = str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT); // 4 more random digits

        return "MPH-{$random}-{$year}{$month}{$day}-{$random2}-{$timestamp}";
    }

    public static function generateMerchantSlug()
    {
        $random = str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT); // 4 random digits

        return "{$random}-".time();
    }

    public function sendOTP()
    {
        if ($this->next_otp_sent_at and $this->next_otp_sent_at > Carbon::now('UTC')) {
            return false;
        }
        // $otp = rand(1001, 9999);
        $otp = '1111';
        $this->update(['otp' => $otp, 'otp_sent_at' => Carbon::now('UTC'), 'next_otp_sent_at' => Carbon::now('UTC')->addMinutes(5)]);

        return $otp;
    }

    public static function getStatusBadge($status)
    {
        if ($status == self::STATUS_DRAFT) {
            return '<span class="inline-block px-3 py-1 border border-yellow-500 bg-yellow-100 text-xs font-medium rounded text-yellow-700 text-center min-w-30"> <i class="ph ph-clock mr-1"></i>En attente</span>';
        } elseif ($status == self::STATUS_ACTIVE) {
            return '<span class="inline-block px-3 py-1 border border-green-500 bg-green-100 text-xs font-medium rounded text-green-700 text-center min-w-30"> <i class="ph ph-check-circle mr-1"></i>Actif</span>';
        } elseif ($status == self::STATUS_SUSPENDED) {
            return '<span class="inline-block px-3 py-1 border border-red-500 bg-red-100 text-xs font-medium rounded text-red-700 text-center min-w-30"> <i class="ph ph-x-circle mr-1"></i>Suspendu</span>';
        }
    }

    public static function getStatusName($status)
    {
        if ($status == self::STATUS_DRAFT) {
            return 'En attente';
        } elseif ($status == self::STATUS_ACTIVE) {
            return 'Actif';
        } elseif ($status == self::STATUS_SUSPENDED) {
            return 'Suspendu';
        }

        return 'N/A';
    }

    public static function getTypeBadge($type)
    {
        if ($type == self::TYPE_PHARMACY) {
            return '<span class="inline-block px-3 py-1 border border-blue-500 bg-blue-100 text-xs font-medium rounded text-blue-700 text-center min-w-30"> <i class="ph ph-building mr-1"></i>Pharmacie</span>';
        } elseif ($type == self::TYPE_DEPOT_PHARMACEUTIQUE) {
            return '<span class="inline-block px-3 py-1 border border-green-500 bg-green-100 text-xs font-medium rounded text-green-700 text-center min-w-30"> <i class="ph ph-buildings mr-1"></i>Depôt pharmaceutique</span>';
        }

        return '<span class="inline-block px-3 py-1 border border-gray-500 bg-gray-100 text-xs font-medium rounded text-gray-700 text-center min-w-30"> <i class="ph ph-tag mr-1"></i>Type non défini</span>';
    }

    public static function getTypeName($type)
    {
        if ($type == self::TYPE_PHARMACY) {
            return 'Pharmacie';
        } elseif ($type == self::TYPE_DEPOT_PHARMACEUTIQUE) {
            return 'Depôt pharmaceutique';
        }

        return 'N/A';
    }

    public function getPharmacyStats()
    {
        $now = now();

        return [
            // [
            //     'title' => 'Produits',
            //     'count' => number_format($this->products()->count()),
            //     'subtitle' => $this->products()->where('is_active', true)->count() . ' actifs',
            //     'change' => '+' . $this->products()->whereMonth('products.created_at', $now->month)->count(),
            //     'trend' => 'up',
            //     'color' => 'yellow',
            //     'icon' => 'ph-package',
            // ],
            [
                'title' => 'Ventes',
                'count' => number_format($this->sales()->count()),
                'subtitle' => 'Total des ventes',
                'change' => '', // You can add monthly change logic
                'trend' => 'up',
                'color' => 'green',
                'icon' => 'ph-shopping-cart',
            ],
            [
                'title' => 'Prescriptions',
                'count' => number_format($this->orders()->count()),
                'subtitle' => 'Total prescrites',
                'change' => '',
                'trend' => 'up',
                'color' => 'blue',
                'icon' => 'ph-clipboard-text',
            ],
            [
                'title' => 'Stock Faible',
                'count' => number_format($this->products()->whereColumn('current_stock', '<=', 'reorder_level')->count()),
                'subtitle' => 'À réapprovisionner',
                'change' => '',
                'trend' => 'down',
                'color' => 'red',
                'icon' => 'ph-warning',
            ],
            [
                'title' => 'Dépenses',
                'count' => number_format($this->expenses()->count()),
                'subtitle' => 'Total des dépenses',
                'change' => '',
                'trend' => 'up',
                'color' => 'purple',
                'icon' => 'ph-receipt',
            ],
        ];
    }

    public function getSalesChart()
    {
        $currentMonth = now();
        $daysInMonth = $currentMonth->daysInMonth;
        $dailySales = collect();

        for ($day = 1; $day <= $daysInMonth; $day++) {
            $date = $currentMonth->copy()->day($day);
            $dailySales->push([
                'day' => $date->format('d'),
                'total' => $this->sales()
                    ->whereYear('created_at', $date->year)
                    ->whereMonth('created_at', $date->month)
                    ->whereDay('created_at', $date->day)
                    ->sum('total_amount'),
            ]);
        }

        return [
            'labels' => $dailySales->pluck('day'),
            'data' => $dailySales->pluck('total'),
        ];
    }

    public function getProductCategoriesChart()
    {
        $categories = Category::whereHas('products', function ($q) {
            $q->where('merchant_id', $this->id);
        })
            ->withCount(['products as count' => function ($q) {
                $q->where('merchant_id', $this->id);
            }])
            ->orderByDesc('count')
            ->take(10)
            ->get();

        return [
            'labels' => $categories->pluck('name'),
            'data' => $categories->pluck('count'),
        ];
    }

    public function getPharmacyRecentSales()
    {
        return $this->sales()->with('customer')->latest()->take(10)->get();
    }

    public function getPharmacyTopProducts()
    {
        return $this->products()->with('category')->orderByDesc('current_stock')->take(10)->get();
    }

    public function getPharmacyRecentPrescriptions()
    {
        return $this->orders()->with('customer')->latest()->take(10)->get();
    }
}
