<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\Employee;
use App\Models\Timelog;
use App\Models\ViberSentMessage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Throwable;

class ViberWebHookController extends Controller
{
    public function index(Request $request)
    {
        $date = date('Y-m-d');
        $employees = Employee::where('department_id', 34)
            ->whereNull('date_resign')
            ->where('classification_id', '<', 3)
            ->pluck('employee_id');
        
        // Get employees who already have messages sent today
        $viberSentMessage = ViberSentMessage::whereIn('employee_id', $employees)
            ->whereDate('created_at', $date)
            ->pluck('employee_id');
        
        // Get time logs for employees who haven't had messages sent
        $bio = Timelog::with([
                'employee:employee_id,firstname,lastname'
            ])
            ->whereDate('datetimelog', $date)
            ->where('in_out', 'I')
            ->where('viber_sent', 0)
            ->whereIn('employee_id', $employees)
            ->whereNotIn('employee_id', $viberSentMessage)
            ->get();
        
        // Check if we have any records to process
        if ($bio->isEmpty()) {
            return response()->json([
                'message' => 'No new time-in records to send.',
                'status' => 'success',
            ], 200);
        }
        
        // Get existing Viber message for today if any
        $viberDateTodayExists = ViberSentMessage::whereDate('created_at', $date)->count();
        $viberMessage = ViberSentMessage::whereDate('created_at', $date)
            ->orderBy('created_at', 'desc')
            ->value('text');
            
        // Prepare the message
        if ($viberDateTodayExists == 0) {
            $message = "$date | TIME IN\n\n1. {$bio[0]->employee->firstname} - " . date('h:i A', strtotime($bio[0]->datetimelog));
            $nextIndex = 2;
        } else {
            // Remove old date header if exists
            $existing = str_replace("$date | TIME IN\n\n", '', $viberMessage);
            // Clean up leading/trailing spaces or extra newlines
            $existing = trim($existing);
            
            // Count how many entries we already have
            $entryCount = substr_count($existing, "\n") + 1;
            $nextIndex = $entryCount + 1;
            
            // Build the initial message with the first new entry
            $message = "$date | TIME IN\n\n" . $existing . "\n" . $nextIndex . ". {$bio[0]->employee->firstname} - " . date('h:i A', strtotime($bio[0]->datetimelog));
            $nextIndex++;
        }
        
        // Get Viber account info
        $getID = Http::withHeaders([
            'X-Viber-Auth-Token' => '549954ab8c73d18d-924fb78e2f6f3a8e-86c2921fe3263177',
        ])->post('https://chatapi.viber.com/pa/get_account_info', [
            'url' => 'https://connectv2.autohub.ph/login',
        ]);
        
        $from = $getID->json();
        
        // Send the message
        $sendText = Http::withHeaders([
            'X-Viber-Auth-Token' => '549954ab8c73d18d-924fb78e2f6f3a8e-86c2921fe3263177',
        ])->post('https://chatapi.viber.com/pa/post', [
            'from' => $from['members'][0]['id'],
            'type' => 'text',
            'text' => $message,
        ]);
        
        // Process all bio records in a single transaction
        DB::connection()->beginTransaction();
        try {
            // Save the first message
            $data = array_merge(
                $sendText->json(),
                [
                    'employee_id' => $bio[0]->employee_id,
                    'from' => $from['members'][0]['id'],
                    'text' => $message,
                    'type' => 'text',
                    'biometric_id' => $bio[0]->id
                ]
            );
            
            // Update the first record as sent
            $updateViberSentToTrue = Timelog::findOrFail($bio[0]->id);
            $updateViberSentToTrue->fill(['viber_sent' => true]);
            $updateViberSentToTrue->save();
            $updateViberSentToTrue->touch();
            
            // Create the message record
            ViberSentMessage::create($data);
            
            // Process the rest of the bio records (starting from index 1)
            for ($i = 1; $i < count($bio); $i++) {
                // Mark as sent
                $updateViberSentToTrue = Timelog::findOrFail($bio[$i]->id);
                $updateViberSentToTrue->fill(['viber_sent' => true]);
                $updateViberSentToTrue->save();
                $updateViberSentToTrue->touch();
                
                // We don't send additional Viber messages for these records
                // But we still track them as processed
            }
            
            DB::connection()->commit();
        } catch (Throwable $e) {
            DB::connection()->rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ]);
        }
        
        return response()->json([
            'message' => 'Record Successfully added!',
            'status' => 'success',
        ], 201);
    }
}
