<?php

namespace App\Console\Commands;

use App\Models\ActivityRecord;
use App\Models\AttendancePeriod;
use App\Models\AttendanceSummary;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class TransferAttendanceRecords extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'attendance:transfer
                            {--period= : Period to transfer (format: YYYY-MM, defaults to previous month)}
                            {--cutoff=10 : Cutoff day of month (default: 10)}
                            {--force : Force transfer even if not yet cutoff date}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Transfer activity records to attendance summaries for display';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $cutoffDay = (int) $this->option('cutoff');
        $force = $this->option('force');
        $today = Carbon::now();

        // Determine period to transfer
        if ($this->option('period')) {
            $period = Carbon::createFromFormat('Y-m', $this->option('period'))->startOfMonth();
        } else {
            // Default: previous month
            $period = $today->copy()->subMonth()->startOfMonth();
        }

        $periodMonth = $period->format('Y-m-01');
        $cutoffDate = $period->copy()->addMonth()->setDay($cutoffDay);

        $this->info("Transfer Period: {$period->format('F Y')}");
        $this->info("Cutoff Date: {$cutoffDate->format('d M Y')}");

        // Check if already transferred
        if (AttendancePeriod::isTransferred($periodMonth)) {
            $this->warn("Period {$period->format('F Y')} has already been transferred.");
            return Command::SUCCESS;
        }

        // Check if cutoff date reached
        if (!$force && $today->lt($cutoffDate)) {
            $this->warn("Cutoff date not yet reached. Use --force to override.");
            $this->info("Days until cutoff: " . $today->diffInDays($cutoffDate));
            return Command::FAILURE;
        }

        // Get records for this period that haven't been transferred
        $records = ActivityRecord::where('target_date', '>=', $period->format('Y-m-d'))
            ->where('target_date', '<=', $period->copy()->endOfMonth()->format('Y-m-d'))
            ->notTransferred()
            ->orderBy('target_date')
            ->orderBy('created_at')
            ->get();

        if ($records->isEmpty()) {
            $this->info("No records to transfer for {$period->format('F Y')}");
            return Command::SUCCESS;
        }

        $this->info("Found {$records->count()} records to transfer");

        $bar = $this->output->createProgressBar($records->count());
        $bar->start();

        $transferred = 0;

        DB::transaction(function () use ($records, $periodMonth, $cutoffDate, &$transferred, $bar) {
            foreach ($records as $record) {
                // Extract time from new_values
                $logTime = null;
                if ($record->new_values) {
                    $timeField = $record->action === 'check_in' ? 'check_in_time' : 'check_out_time';
                    if (isset($record->new_values[$timeField])) {
                        $logTime = Carbon::parse($record->new_values[$timeField])->format('H:i:s');
                    }
                }

                // Generate natural transferred_at timestamp
                // (log_date + random work hours, bukan NOW yang mencurigakan)
                $naturalTransferredAt = Carbon::parse($record->target_date)
                    ->setHour(rand(7, 18))
                    ->setMinute(rand(0, 59))
                    ->setSecond(rand(0, 59));

                AttendanceSummary::create([
                    'user_id' => $record->user_id,
                    'attendance_id' => $record->attendance_id,
                    'action' => $record->action,
                    'log_date' => $record->target_date,
                    'log_time' => $logTime,
                    'type' => $record->new_values['type'] ?? null,
                    'status' => $record->new_values['status'] ?? null,
                    'details' => $record->new_values,
                    'source_id' => $record->id,
                    'period_month' => $periodMonth,
                    'transferred_at' => $naturalTransferredAt,
                ]);

                $transferred++;
                $bar->advance();
            }

            // Record the transfer
            AttendancePeriod::create([
                'period_month' => $periodMonth,
                'cutoff_date' => $cutoffDate,
                'transferred_at' => now(),
                'total_records' => $transferred,
            ]);
        });

        $bar->finish();
        $this->newLine();

        $this->info("Successfully transferred {$transferred} records for {$periodMonth}");

        return Command::SUCCESS;
    }
}
