<?php

namespace App\Console\Commands;

use App\Jobs\DailyAICallReportJob;
use Illuminate\Console\Command;
use App\Model\Master\Client;

class DailyAICallReportCron extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:send:daily-ai-call-report {--clientId=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send daily AI call report to all clients with AI enabled';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->logToFile("DAILY_AI_CRON_START - " . date('Y-m-d H:i:s'));

        $clientId = $this->option('clientId');

        if ($clientId) {
            $this->info("DailyAICallReportJob({$clientId})");
            $this->logToFile("DAILY_AI_CRON_SINGLE_CLIENT - Client ID: {$clientId}");
            dispatch(new DailyAICallReportJob($clientId))->onConnection("database");
        } else {
            // Only get clients with AI outbound enabled
            $clients = Client::where('outbond_ai', 1)->get();
            
            $this->logToFile("DAILY_AI_CRON_ALL_CLIENTS - Total AI-enabled clients: " . count($clients));
            
            foreach ($clients as $client) {
                $this->info("DailyAICallReportJob({$client->id})");
                $this->logToFile("DAILY_AI_CRON_DISPATCH - Client ID: {$client->id}, Client Name: {$client->name}");
                dispatch(new DailyAICallReportJob($client->id))->onConnection("database");
            }
            
            $this->info("Dispatched " . count($clients) . " DailyAICallReportJob(s)");
            $this->logToFile("DAILY_AI_CRON_COMPLETE - Dispatched " . count($clients) . " jobs");
        }
    }

    /**
     * Log to file (file-based logging)
     */
    private function logToFile($message)
    {
        $logFile = storage_path('app/daily_ai_call_report.log');
        $timestamp = date('Y-m-d H:i:s');
        $logMessage = "[{$timestamp}] {$message}\n";
        file_put_contents($logFile, $logMessage, FILE_APPEND);
    }
}

