<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'category_id',
        'serial_no',
        'imei',
        'barcode',
        'image',
        'product_name',
        'quality',
        'description',
        'color',
        'condition',
        'status',
        'distributor_name',
        'distributor_code',
        'distributor_contact',
        'distributor_address',
        'retailer_name',
        'retailer_code',
        'retailer_contact',
        'retailer_address',
        'retailer_assigned_at',
        'client_name',
        'client_phone',
        'client_email',
        'client_address',
        'sold_at',
        'price',
        'discount_price',
        'cost',
        'warranty_period',
        'manufacture_date',
        'expiry_date',
        'batch_number',
        'supplier_name',
        'location',
        'notes',
        'scanned_by',
        'scanned_at',
        'created_by',
        'updated_by',
        'verification_token'
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'color' => 'array',
        'gallery_images' => 'array',
    ];
    /**
     * Get the category that the product belongs to.
     */
    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    /**
     * Fill new product instance from scan data
     */
    public function fillFromScan($scanData)
    {
        $scanData = trim($scanData);

        \Log::info("Processing scan data: {$scanData}");

        // Determine what type of data we have
        if (preg_match('/^\d{15}$/', $scanData)) { // IMEI
            $this->imei = $scanData;
            // Generate a predictable serial number from the IMEI
            $this->serial_no = 'SN-IMEI-' . substr($scanData, -8);
        } else if (preg_match('/^(SN-|S-)/i', $scanData)) { // Serial
            $this->serial_no = $scanData;
            // IMEI will be filled manually in the form
        } else { // Assume Barcode or other format
            $this->barcode = $scanData;
            // Generate a predictable serial number from the barcode
            $this->serial_no = 'SN-BC-' . strtoupper(substr(preg_replace('/[^a-zA-Z0-9]/', '', $scanData), -8));
            // Use the barcode data as the IMEI as requested
            $this->imei = $scanData;
        }

        $this->fill([
            'product_name' => 'Scanned Product - ' . date('Y-m-d H:i:s'),
            'quality' => 'Authentic',
            'color' => 'Unknown',
            'condition' => 'New', // Ensure condition has a default value
            'status' => 'In Warehouse',
            'distributor_name' => 'System Generated',
            'distributor_code' => 'D-SCAN-' . strtoupper(substr(str_shuffle("0123456789"), 0, 6)),
        ]);

        $this->wasRecentlyCreated = true;

        \Log::info("New product instance prepared for scan data: {$scanData}");

        return $this;
    }

    /**
     * Scope for search functionality
     */
    public function scopeSearch($query, $search)
    {
        if ($search) {
            return $query->where(function($q) use ($search) {
                $q->where('serial_no', 'like', "%{$search}%")
                  ->orWhere('imei', 'like', "%{$search}%")
                  ->orWhere('barcode', 'like', "%{$search}%")
                  ->orWhere('product_name', 'like', "%{$search}%")
                  ->orWhere('distributor_name', 'like', "%{$search}%")
                  ->orWhere('retailer_name', 'like', "%{$search}%")
                  ->orWhere('client_name', 'like', "%{$search}%");
            });
        }
        return $query;
    }

    /**
     * Get recently scanned products
     */
    public static function recentlyScanned($hours = 24)
    {
        return self::where('scanned_at', '>=', now()->subHours($hours))
                   ->orderBy('scanned_at', 'desc');
    }
}
