<?php

namespace App\Traits;

use Illuminate\Support\Facades\DB;

trait TracksManualEdits
{
    /**
     * Mark category fields as manually edited
     * Call this in your update controller AFTER updating
     */
    public function markCategoryManualEdit($categoryId, array $fields)
    {
        $updateData = [];
        
        if (in_array('image', $fields)) {
            $updateData['manual_image'] = true;
        }
        
        if (in_array('description', $fields)) {
            $updateData['manual_description'] = true;
        }
        
        if (in_array('name', $fields)) {
            $updateData['manual_name'] = true;
        }
        
        if (!empty($updateData)) {
            DB::table('categories')
                ->where('id', $categoryId)
                ->update($updateData);
        }
    }
    
    /**
     * Mark product fields as manually edited
     */
    public function markProductManualEdit($productId, array $fields)
    {
        $updateData = [];
        
        if (in_array('image', $fields)) {
            $updateData['manual_image'] = true;
        }
        
        if (in_array('description', $fields)) {
            $updateData['manual_description'] = true;
        }
        
        if (in_array('name', $fields)) {
            $updateData['manual_name'] = true;
        }
        
        if (in_array('selling_price', $fields) || in_array('price', $fields)) {
            $updateData['manual_price'] = true;
        }
        
        if (!empty($updateData)) {
            DB::table('products')
                ->where('id', $productId)
                ->update($updateData);
        }
    }
    
    /**
     * Reset manual flags (when admin wants to allow API sync again)
     */
    public function resetCategoryManualFlags($categoryId)
    {
        DB::table('categories')
            ->where('id', $categoryId)
            ->update([
                'manual_image' => false,
                'manual_description' => false,
                'manual_name' => false,
            ]);
    }
    
    /**
     * Reset product manual flags
     */
    public function resetProductManualFlags($productId)
    {
        DB::table('products')
            ->where('id', $productId)
            ->update([
                'manual_image' => false,
                'manual_description' => false,
                'manual_name' => false,
                'manual_price' => false,
            ]);
    }
}