<?php

namespace Database\Seeders;

use App\Models\User;
use App\Models\Client;
use App\Models\Conveyance;
use Carbon\Carbon;
use Carbon\CarbonPeriod;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class DemoConveyanceSeeder extends Seeder
{
    public function run(): void
    {
        // ----------------------------------------------------
        // 1. Employees (15)
        // ----------------------------------------------------
        $employeesData = [
            ['name' => 'Sartaj Akhtar',   'email' => 'sartaj.akhtar@pactech.com'],
            ['name' => 'David Kumar',     'email' => 'david.kumar@pactech.com'],
            ['name' => 'Priya Sharma',    'email' => 'priya.sharma@pactech.com'],
            ['name' => 'Rahul Verma',     'email' => 'rahul.verma@pactech.com'],
            ['name' => 'Anita Joshi',     'email' => 'anita.joshi@pactech.com'],
            ['name' => 'Rohan Mehta',     'email' => 'rohan.mehta@pactech.com'],
            ['name' => 'Nitin Aggarwal',  'email' => 'nitin.aggarwal@pactech.com'],
            ['name' => 'Sneha Patil',     'email' => 'sneha.patil@pactech.com'],
            ['name' => 'Vivek Singh',     'email' => 'vivek.singh@pactech.com'],
            ['name' => 'Meera Nair',      'email' => 'meera.nair@pactech.com'],
            ['name' => 'Amit Jain',       'email' => 'amit.jain@pactech.com'],
            ['name' => 'Riya Kapoor',     'email' => 'riya.kapoor@pactech.com'],
            ['name' => 'Karan Malhotra',  'email' => 'karan.malhotra@pactech.com'],
            ['name' => 'Neha Gupta',      'email' => 'neha.gupta@pactech.com'],
            ['name' => 'Arjun Desai',     'email' => 'arjun.desai@pactech.com'],
        ];

        $employees = [];

        foreach ($employeesData as $emp) {
            $user = User::updateOrCreate(
                ['email' => $emp['email']],
                [
                    'name'     => $emp['name'],
                    'password' => Hash::make('password'),
                    'role'     => 'employee',
                ]
            );

            $employees[] = $user;
        }

        // ----------------------------------------------------
        // 2. Clients
        // ----------------------------------------------------
        $clientsData = [
            ['name' => 'ABC Manufacturing Pvt Ltd', 'city' => 'Mumbai'],
            ['name' => 'Global Finserv LLP',        'city' => 'Delhi'],
            ['name' => 'Sunrise Hospitals',         'city' => 'Bengaluru'],
            ['name' => 'Evergreen Realty',          'city' => 'Pune'],
        ];

        $clients = [];
        foreach ($clientsData as $c) {
            $client = Client::updateOrCreate(
                ['name' => $c['name']],
                [
                    'city'      => $c['city'],
                    'is_active' => true,
                ]
            );
            $clients[] = $client;
        }

        // ----------------------------------------------------
        // 3. Conveyance rows – random, for current claim month
        // ----------------------------------------------------
        $today = Carbon::today();
        $targetMonth = ($today->day <= 10)
            ? $today->copy()->subMonthNoOverflow()
            : $today->copy();

        $monthStart = $targetMonth->copy()->startOfMonth();
        $monthEnd   = $targetMonth->copy()->endOfMonth();

        $period = CarbonPeriod::create($monthStart, $monthEnd);

        $modes         = ['Auto', 'Cab', 'Metro', 'Bus', 'Own Car'];
        $fromLocations = ['Home', 'PAC Office', 'Client Site', 'Branch Office'];
        $toLocations   = ['PAC Office', 'Client Site', 'Branch Office', 'Home'];

        Conveyance::truncate();

        $insertRows = [];

        foreach ($employees as $emp) {
            foreach ($period as $date) {
                $tripCount = rand(0, 2);

                for ($i = 0; $i < $tripCount; $i++) {

                    $client     = $clients[array_rand($clients)];
                    $mode       = $modes[array_rand($modes)];
                    $from       = $fromLocations[array_rand($fromLocations)];
                    $to         = $toLocations[array_rand($toLocations)];
                    $baseAmount = rand(80, 600);
                    $status     = (rand(1, 100) <= 80) ? 'submitted' : 'draft';

                    $isReturn      = rand(1, 100) <= 40;
                    $returnAmount  = null;
                    $returnRemarks = null;
                    $hasDiff       = false;

                    if ($isReturn) {
                        if (rand(0, 1) === 1) {
                            $returnAmount = $baseAmount;
                        } else {
                            $diff         = rand(-30, 50);
                            $returnAmount = max(50, $baseAmount + $diff);
                            $hasDiff      = true;
                            $returnRemarks = 'Return fare different from onward (seed data)';
                        }
                    }

                    $insertRows[] = [
                        'user_id'        => $emp->id,
                        'date'           => $date->toDateString(),
                        'from_location'  => $from,
                        'to_location'    => $to,
                        'client_id'      => $client->id,
                        'mode'           => $mode,
                        'amount'         => $baseAmount,
                        'remarks'        => 'Seeded trip ' . ($hasDiff ? '(R* demo)' : ''),
                        'is_return'      => $isReturn,
                        'return_amount'  => $returnAmount,
                        'return_remarks' => $returnRemarks,
                        'status'         => $status,
                        'created_at'     => now(),
                        'updated_at'     => now(),
                    ];
                }
            }
        }

        if (!empty($insertRows)) {
            Conveyance::insert($insertRows);
        }
    }
}
