<?php

namespace Database\Seeders;

use Log;
use Carbon\Carbon;
use App\Models\User;
use App\Models\Referral;
use Faker\Factory as Faker;
use Illuminate\Support\Str;
use Illuminate\Database\Seeder;
use App\Models\PointsTransaction;
use Illuminate\Support\Facades\DB;

class ReferralMarketingSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker::create('ar_SA'); // Use Arabic locale for realistic messages

        // Fetch existing users
        $users = User::all();

        if ($users->isEmpty()) {
            //  Log::warning('No existing users found in the database. Seeder cannot proceed.');
            return;
        }

        // Clear existing referrals, points transactions, and notifications (optional, comment out if not desired)
        Referral::truncate();
        PointsTransaction::truncate();
        DB::table('notifications')->truncate();

        // Reset points for all users to ensure consistency
        User::query()->update(['points' => 0]);

        // Create referrals (randomly assign some users as referrers)
        foreach ($users as $index => $user) {
            if ($index === 0)
                continue; // Skip first user to avoid self-referral

            // 50% chance a user was referred by another
            if ($faker->boolean(50)) {
                $referrer = $faker->randomElement($users->slice(0, $index)->all()); // Pick a previous user
                $referralCreatedAt = $faker->dateTimeBetween(
                    $referrer->created_at,
                    $user->created_at->gt($referrer->created_at) ? $user->created_at : Carbon::now()
                );

                // Create referral
                Referral::create([
                    'referrer_id' => $referrer->id,
                    'referred_id' => $user->id,
                    'created_at' => $referralCreatedAt,
                    'updated_at' => $referralCreatedAt,
                ]);

                // Award referrer points for signup (100 points)
                PointsTransaction::create([
                    'user_id' => $referrer->id,
                    'points' => 100,
                    'action_type' => 'referral_signup',
                    'related_id' => $user->id,
                    'created_at' => $referralCreatedAt,
                    'updated_at' => $referralCreatedAt,
                ]);

                // Update referrer's points
                $referrer->increment('points', 100);

                // Create notification for referral
                DB::table('notifications')->insert([
                    'id' => Str::uuid(),
                    'type' => 'App\\Notifications\\ReferralBonus',
                    'notifiable_type' => User::class,
                    'notifiable_id' => $referrer->id,
                    'data' => json_encode([
                        'message' => "لقد حصلت على 100 نقطة لتسجيل {$user->full_name} عبر رابط الإحالة الخاص بك",
                    ]),
                    'read_at' => $faker->boolean(30)
                        ? \Carbon\Carbon::parse($referralCreatedAt)->addHours($faker->numberBetween(1, 48))
                        : null,
                    'created_at' => $referralCreatedAt,
                    'updated_at' => $referralCreatedAt,
                ]);
            }
        }

        // Create points transactions and notifications for product and website shares
        foreach ($users as $user) {
            // Random number of shares (0–5 per user)
            $shareCount = $faker->numberBetween(0, 5);
            for ($i = 0; $i < $shareCount; $i++) {
                $actionType = $faker->randomElement(['product_share', 'website_share']); // Fixed: Use randomElement
                $shareCreatedAt = $faker->dateTimeBetween($user->created_at, Carbon::now());

                // Create points transaction
                PointsTransaction::create([
                    'user_id' => $user->id,
                    'points' => 50, // 50 points per share
                    'action_type' => $actionType,
                    'related_id' => $actionType === 'product_share' ? $faker->numberBetween(1, 100) : null, // Random product ID
                    'created_at' => $shareCreatedAt,
                    'updated_at' => $shareCreatedAt,
                ]);

                // Update user's points
                $user->increment('points', 50);

                // Create notification for share
                $message = $actionType === 'product_share'
                    ? "لقد حصلت على 50 نقطة لمشاركة منتج"
                    : "لقد حصلت على 50 نقطة لمشاركة الموقع";
                DB::table('notifications')->insert([
                    'id' => Str::uuid(),
                    'type' => 'App\\Notifications\\ShareBonus',
                    'notifiable_type' => User::class,
                    'notifiable_id' => $user->id,
                    'data' => json_encode(['message' => $message]),
                    'read_at' => $faker->boolean(30)
                        ? \Carbon\Carbon::parse($referralCreatedAt)->addHours($faker->numberBetween(1, 48))
                        : null,
                    'created_at' => $shareCreatedAt,
                    'updated_at' => $shareCreatedAt,
                ]);
            }
        }
    }
}