<?php

namespace App\Jobs;

use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Model\Master\Client;

class DailyAICallReportJob extends Job
{
    /**
     * The number of times the job may be attempted.
     *
     * @var int
     */
    public $tries = 1;
    public $timeout = 300;

    private $clientId;

    // ========== EMAIL RECIPIENT TOGGLE ==========
    // Set to true to send email to admin (ADMIN_NOTIFY_EMAIL env) 
    // Set to false to send email to client owner
    private $SEND_TO_ADMIN = true;
    // ============================================

    /**
     * DailyAICallReportJob constructor.
     * @param $clientId
     */
    public function __construct($clientId)
    {
        $this->clientId = $clientId;
    }

    /**
     * Execute the job.
     */
    public function handle()
    {
        $this->logToFile("DAILY_AI_REPORT_START - Client ID: {$this->clientId}, Attempt: {$this->attempts()}");

        try {
            $connection = 'mysql_' . $this->clientId;
            
            // Get client info
            $client = Client::find($this->clientId);
            if (!$client) {
                $this->logToFile("ERROR: DAILY_AI_REPORT_CLIENT_NOT_FOUND - Client ID: {$this->clientId}");
                return;
            }

            $clientName = $client->name ?? "Client #{$this->clientId}";
            $this->logToFile("DAILY_AI_REPORT_CLIENT_FOUND - Client: {$clientName}");

            // Get yesterday's date range (UTC)
            $yesterday = Carbon::yesterday()->format('Y-m-d');
            $startOfDay = $yesterday . ' 00:00:00';
            $endOfDay = $yesterday . ' 23:59:59';

            $this->logToFile("DAILY_AI_REPORT_DATE_RANGE - Date: {$yesterday}, Start: {$startOfDay}, End: {$endOfDay}");

            // ========== AGGREGATE DATA BY ROUTE (IN/OUT) ==========
            // Get incoming calls stats (route = 'IN')
            $incomingStats = DB::connection($connection)
                ->table('cdr_ai')
                ->select([
                    DB::raw('COUNT(*) as total_calls'),
                    DB::raw('COALESCE(SUM(duration), 0) as total_duration_seconds'),
                    DB::raw('COALESCE(AVG(duration), 0) as avg_duration_seconds'),
                    DB::raw('COALESCE(SUM(unit_minute), 0) as total_billable_minutes'),
                    DB::raw('COALESCE(SUM(cost), 0) as total_cost')
                ])
                ->where('route', 'IN')
                ->whereBetween('start_time', [$startOfDay, $endOfDay])
                ->first();

            // Get outgoing calls stats (route = 'OUT')
            $outgoingStats = DB::connection($connection)
                ->table('cdr_ai')
                ->select([
                    DB::raw('COUNT(*) as total_calls'),
                    DB::raw('COALESCE(SUM(duration), 0) as total_duration_seconds'),
                    DB::raw('COALESCE(AVG(duration), 0) as avg_duration_seconds'),
                    DB::raw('COALESCE(SUM(unit_minute), 0) as total_billable_minutes'),
                    DB::raw('COALESCE(SUM(cost), 0) as total_cost')
                ])
                ->where('route', 'OUT')
                ->whereBetween('start_time', [$startOfDay, $endOfDay])
                ->first();

            // Aggregate data from cdr_ai for yesterday (campaign-wise)
            $campaignStats = DB::connection($connection)
                ->table('cdr_ai')
                ->select([
                    'campaign_id',
                    'route',
                    DB::raw('COUNT(*) as total_calls'),
                    DB::raw('COALESCE(SUM(duration), 0) as total_duration_seconds'),
                    DB::raw('COALESCE(AVG(duration), 0) as avg_duration_seconds'),
                    DB::raw('COALESCE(SUM(unit_minute), 0) as total_billable_minutes'),
                    DB::raw('COALESCE(SUM(cost), 0) as total_cost')
                ])
                ->whereBetween('start_time', [$startOfDay, $endOfDay])
                ->groupBy('campaign_id', 'route')
                ->get();

            // Check if any data exists
            $totalIncoming = $incomingStats->total_calls ?? 0;
            $totalOutgoing = $outgoingStats->total_calls ?? 0;
            
            if ($totalIncoming == 0 && $totalOutgoing == 0) {
                $this->logToFile("DAILY_AI_REPORT_NO_DATA - Client ID: {$this->clientId}, Date: {$yesterday}");
                return;
            }

            $this->logToFile("DAILY_AI_REPORT_DATA_FOUND - Incoming: {$totalIncoming}, Outgoing: {$totalOutgoing}");

            // Get campaign names
            $campaignIds = $campaignStats->pluck('campaign_id')->unique()->toArray();
            $campaigns = DB::connection($connection)
                ->table('campaign')
                ->whereIn('id', $campaignIds)
                ->pluck('title', 'id')
                ->toArray();

            // Calculate overall totals
            $overallTotalCalls = $totalIncoming + $totalOutgoing;
            $overallTotalDuration = ($incomingStats->total_duration_seconds ?? 0) + ($outgoingStats->total_duration_seconds ?? 0);
            $overallBillableMinutes = ($incomingStats->total_billable_minutes ?? 0) + ($outgoingStats->total_billable_minutes ?? 0);
            $overallTotalCost = ($incomingStats->total_cost ?? 0) + ($outgoingStats->total_cost ?? 0);
            $overallAvgDuration = $overallTotalCalls > 0 ? $overallTotalDuration / $overallTotalCalls : 0;

            $this->logToFile("DAILY_AI_REPORT_TOTALS - Calls: {$overallTotalCalls}, Duration: {$overallTotalDuration}s, Billable: {$overallBillableMinutes}min, Cost: {$overallTotalCost}");

            // Determine recipient email
            if ($this->SEND_TO_ADMIN) {
                $recipientEmail = env('ADMIN_NOTIFY_EMAIL');
                $recipientName = 'Admin';
                $this->logToFile("DAILY_AI_REPORT_RECIPIENT_ADMIN - Email: {$recipientEmail}");
            } else {
                // Get client owner email
                $owner = DB::connection('master')
                    ->table('users')
                    ->where('parent_id', $this->clientId)
                    ->where('role', 'owner')
                    ->first();
                
                if (!$owner || empty($owner->email)) {
                    $this->logToFile("ERROR: DAILY_AI_REPORT_OWNER_NOT_FOUND - Client ID: {$this->clientId}");
                    return;
                }
                $recipientEmail = $owner->email;
                $recipientName = $owner->name ?? 'Client';
                $this->logToFile("DAILY_AI_REPORT_RECIPIENT_OWNER - Email: {$recipientEmail}");
            }

            if (empty($recipientEmail)) {
                $this->logToFile("ERROR: DAILY_AI_REPORT_NO_RECIPIENT - Client ID: {$this->clientId}");
                return;
            }

            // Build email body
            $emailBody = $this->buildEmailBody(
                $recipientName,
                $clientName,
                $yesterday,
                $incomingStats,
                $outgoingStats,
                $campaignStats,
                $campaigns,
                $overallTotalCalls,
                $overallTotalDuration,
                $overallAvgDuration,
                $overallBillableMinutes,
                $overallTotalCost,
                $client->currency_code ?? 'INR'
            );

            // Send email
            $subject = "Daily AI Call Report - {$yesterday}";
            send_sendgrid_mail($recipientEmail, $subject, $emailBody);

            $this->logToFile("DAILY_AI_REPORT_EMAIL_SENT - Recipient: {$recipientEmail}, Date: {$yesterday}, Total Calls: {$overallTotalCalls}");

        } catch (\Throwable $e) {
            $this->logToFile("ERROR: DAILY_AI_REPORT_EXCEPTION - Client ID: {$this->clientId}, Error: {$e->getMessage()}");
            Log::error("DailyAICallReportJob.handle.error", [
                'clientId' => $this->clientId,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
        }
    }

    /**
     * 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);
    }

    /**
     * Format seconds to human-readable duration
     */
    private function formatDuration($seconds)
    {
        $hours = floor($seconds / 3600);
        $minutes = floor(($seconds % 3600) / 60);
        $secs = $seconds % 60;

        if ($hours > 0) {
            return sprintf('%02d Hour %02d Minutes', $hours, $minutes);
        }
        return sprintf('%02d Minutes %02d Seconds', $minutes, $secs);
    }

    /**
     * Format average duration (minutes and seconds)
     */
    private function formatAvgDuration($seconds)
    {
        $minutes = floor($seconds / 60);
        $secs = round($seconds % 60);
        return sprintf('%d Minutes %02d Seconds', $minutes, $secs);
    }

    /**
     * Build the HTML email body
     */
    private function buildEmailBody(
        $recipientName,
        $clientName,
        $date,
        $incomingStats,
        $outgoingStats,
        $campaignStats,
        $campaigns,
        $totalCalls,
        $totalDuration,
        $avgDuration,
        $billableMinutes,
        $totalCost,
        $currencyCode
    ) {
        $currencySymbol = $currencyCode === 'INR' ? '₹' : '$';

        // Incoming/Outgoing values
        $inCalls = $incomingStats->total_calls ?? 0;
        $inDuration = $incomingStats->total_duration_seconds ?? 0;
        $inAvgDuration = $incomingStats->avg_duration_seconds ?? 0;
        $inBillable = $incomingStats->total_billable_minutes ?? 0;
        $inCost = $incomingStats->total_cost ?? 0;

        $outCalls = $outgoingStats->total_calls ?? 0;
        $outDuration = $outgoingStats->total_duration_seconds ?? 0;
        $outAvgDuration = $outgoingStats->avg_duration_seconds ?? 0;
        $outBillable = $outgoingStats->total_billable_minutes ?? 0;
        $outCost = $outgoingStats->total_cost ?? 0;

        // Build campaign-wise breakdown rows
        $campaignRows = '';
        $campaignGrouped = [];
        
        foreach ($campaignStats as $stat) {
            $cid = $stat->campaign_id;
            if (!isset($campaignGrouped[$cid])) {
                $campaignGrouped[$cid] = ['IN' => null, 'OUT' => null];
            }
            $campaignGrouped[$cid][$stat->route] = $stat;
        }

        foreach ($campaignGrouped as $campaignId => $routes) {
            $campaignName = $campaigns[$campaignId] ?? "Campaign #{$campaignId}";
            
            // Outgoing row
            if ($routes['OUT']) {
                $stat = $routes['OUT'];
                $campaignRows .= "
                    <tr style='background: #e8f5e9;'>
                        <td style='border: 1px solid #ddd; padding: 10px;'>{$campaignName}</td>
                        <td style='border: 1px solid #ddd; padding: 10px; text-align: center;'><strong>OUT</strong></td>
                        <td style='border: 1px solid #ddd; padding: 10px; text-align: center;'>{$stat->total_calls}</td>
                        <td style='border: 1px solid #ddd; padding: 10px; text-align: center;'>{$this->formatDuration($stat->total_duration_seconds)}</td>
                        <td style='border: 1px solid #ddd; padding: 10px; text-align: center;'>{$this->formatAvgDuration($stat->avg_duration_seconds)}</td>
                        <td style='border: 1px solid #ddd; padding: 10px; text-align: center;'>{$stat->total_billable_minutes}</td>
                        <td style='border: 1px solid #ddd; padding: 10px; text-align: right;'>{$currencySymbol}" . number_format($stat->total_cost, 2) . "</td>
                    </tr>
                ";
            }
            
            // Incoming row
            if ($routes['IN']) {
                $stat = $routes['IN'];
                $campaignRows .= "
                    <tr style='background: #e3f2fd;'>
                        <td style='border: 1px solid #ddd; padding: 10px;'>{$campaignName}</td>
                        <td style='border: 1px solid #ddd; padding: 10px; text-align: center;'><strong>IN</strong></td>
                        <td style='border: 1px solid #ddd; padding: 10px; text-align: center;'>{$stat->total_calls}</td>
                        <td style='border: 1px solid #ddd; padding: 10px; text-align: center;'>{$this->formatDuration($stat->total_duration_seconds)}</td>
                        <td style='border: 1px solid #ddd; padding: 10px; text-align: center;'>{$this->formatAvgDuration($stat->avg_duration_seconds)}</td>
                        <td style='border: 1px solid #ddd; padding: 10px; text-align: center;'>{$stat->total_billable_minutes}</td>
                        <td style='border: 1px solid #ddd; padding: 10px; text-align: right;'>{$currencySymbol}" . number_format($stat->total_cost, 2) . "</td>
                    </tr>
                ";
            }
        }

        return "
            <div style='font-family: Arial, sans-serif; max-width: 900px; margin: 0 auto; padding: 20px;'>
                <h2 style='color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 10px;'>
                    Daily AI Call Report
                </h2>
                
                <p style='font-size: 16px; color: #34495e;'>
                    Hello <strong>{$recipientName}</strong>,
                </p>
                
                <p style='font-size: 15px; color: #555;'>
                    Please find below the summary of AI calling activity for <strong>{$clientName}</strong>:
                </p>
                
                <div style='background: #f8f9fa; padding: 15px; border-radius: 8px; margin: 20px 0;'>
                    <p style='margin: 0; font-size: 18px; color: #2c3e50;'>
                        <strong>Date:</strong> {$date}
                    </p>
                </div>

                <!-- ========== CALL SUMMARY (IN/OUT + TOTAL) ========== -->
                <h3 style='color: #2c3e50; margin-top: 30px;'>Call Summary</h3>
                
                <table style='width: 100%; border-collapse: collapse; margin: 15px 0;'>
                    <tr style='background: #34495e; color: white;'>
                        <th style='padding: 12px; text-align: left;'>IN/OUT</th>
                        <th style='padding: 12px; text-align: center;'>Calls</th>
                        <th style='padding: 12px; text-align: center;'>Talk Time</th>
                        <th style='padding: 12px; text-align: center;'>Avg Duration</th>
                        <th style='padding: 12px; text-align: center;'>Billable Min</th>
                        <th style='padding: 12px; text-align: right;'>Charge</th>
                    </tr>
                    <tr style='background: #e8f5e9;'>
                        <td style='padding: 12px; border: 1px solid #ddd;'><strong>Outgoing (OUT)</strong></td>
                        <td style='padding: 12px; border: 1px solid #ddd; text-align: center;'>{$outCalls}</td>
                        <td style='padding: 12px; border: 1px solid #ddd; text-align: center;'>{$this->formatDuration($outDuration)}</td>
                        <td style='padding: 12px; border: 1px solid #ddd; text-align: center;'>{$this->formatAvgDuration($outAvgDuration)}</td>
                        <td style='padding: 12px; border: 1px solid #ddd; text-align: center;'>{$outBillable}</td>
                        <td style='padding: 12px; border: 1px solid #ddd; text-align: right;'>{$currencySymbol}" . number_format($outCost, 2) . "</td>
                    </tr>
                    <tr style='background: #e3f2fd;'>
                        <td style='padding: 12px; border: 1px solid #ddd;'><strong>Incoming (IN)</strong></td>
                        <td style='padding: 12px; border: 1px solid #ddd; text-align: center;'>{$inCalls}</td>
                        <td style='padding: 12px; border: 1px solid #ddd; text-align: center;'>{$this->formatDuration($inDuration)}</td>
                        <td style='padding: 12px; border: 1px solid #ddd; text-align: center;'>{$this->formatAvgDuration($inAvgDuration)}</td>
                        <td style='padding: 12px; border: 1px solid #ddd; text-align: center;'>{$inBillable}</td>
                        <td style='padding: 12px; border: 1px solid #ddd; text-align: right;'>{$currencySymbol}" . number_format($inCost, 2) . "</td>
                    </tr>
                    <tr style='background: #2c3e50; color: white;'>
                        <td style='padding: 12px; border: 1px solid #ddd;'><strong>TOTAL</strong></td>
                        <td style='padding: 12px; border: 1px solid #ddd; text-align: center; font-weight: bold;'>{$totalCalls}</td>
                        <td style='padding: 12px; border: 1px solid #ddd; text-align: center; font-weight: bold;'>{$this->formatDuration($totalDuration)}</td>
                        <td style='padding: 12px; border: 1px solid #ddd; text-align: center; font-weight: bold;'>{$this->formatAvgDuration($avgDuration)}</td>
                        <td style='padding: 12px; border: 1px solid #ddd; text-align: center; font-weight: bold;'>{$billableMinutes}</td>
                        <td style='padding: 12px; border: 1px solid #ddd; text-align: right; font-weight: bold; font-size: 16px;'>{$currencySymbol}" . number_format($totalCost, 2) . "</td>
                    </tr>
                </table>
                
                <!-- ========== CAMPAIGN-WISE BREAKDOWN ========== -->
                <h3 style='color: #2c3e50; margin-top: 30px;'>Campaign-Wise Breakdown</h3>
                
                <table style='width: 100%; border-collapse: collapse; margin: 15px 0;'>
                    <tr style='background: #34495e; color: white;'>
                        <th style='padding: 10px; text-align: left;'>Campaign Name</th>
                        <th style='padding: 10px; text-align: center;'>IN/OUT</th>
                        <th style='padding: 10px; text-align: center;'>Calls</th>
                        <th style='padding: 10px; text-align: center;'>Talk Time</th>
                        <th style='padding: 10px; text-align: center;'>Avg Duration</th>
                        <th style='padding: 10px; text-align: center;'>Billable Min</th>
                        <th style='padding: 10px; text-align: right;'>Charge</th>
                    </tr>
                    {$campaignRows}
                </table>
                
                <hr style='border: none; border-top: 1px solid #ddd; margin: 30px 0;'>
                
                <p style='color: #7f8c8d; font-size: 13px;'>
                    This is an automated daily report generated at UTC 00:00.<br>
                    Client: {$clientName}
                </p>
            </div>
        ";
    }
}
