<?php

namespace App\Services;

use App\Models\Client;
use App\Models\ClientEditLog;
use App\Models\Pop;
use App\Classes\MikrotikService\SyncWithMk;
use App\Services\RadiusClientSync;
use Illuminate\Support\Facades\DB;

class BatchPopChangeService
{
    public function batchPopChange($client, $newPopId, $authUserId)
    {
        DB::beginTransaction();
        try {
            // Reload client with relationships
            $client = Client::with('clientsinfo', 'pop.reseller')->find($client->id);
            $oldClientData = $client;
            $oldPop = $client->pop;

            if (!$oldPop) {
                throw new \Exception("Old POP not found for client");
            }

            // Load old pop with reseller relationship if not loaded
            if (!$oldPop->relationLoaded('reseller')) {
                $oldPop->load('reseller');
            }

            $newPop = Pop::with('nas', 'reseller')->find($newPopId);

            if (!$newPop) {
                throw new \Exception("POP not found");
            }

            // Store original billing_start_date before any changes
            $originalBillingStartDate = $client->billing_start_date;

            // Update client POP
            $client->pop_id = $newPopId;

            // Handle billing start date if reseller type changes (matching ClientController logic)
            $billingStartDateChanged = false;
            if (globalPermission('save_billing_start_date_on_reseller_change')) {
                if ($oldPop->reseller_id != $newPop->reseller_id) {
                    if ($newPop->reseller && $oldPop->reseller && $newPop->reseller->reseller_type == 'own' && $oldPop->reseller->reseller_type == 'other') {
                        $client->billing_start_date = now();
                        $billingStartDateChanged = true;
                    }
                } else {
                    if ($newPop->reseller && $newPop->reseller->reseller_type == 'own' && $newPop->subreseller == 'yes' && $oldPop->subreseller == 'no') {
                        $client->billing_start_date = now();
                        $billingStartDateChanged = true;
                    }
                }
            }

            $client->save();

            // Store only changed fields in simple format
            $oldChangedData = [
                'pop_id' => $oldPop->id,
                'clientsinfo' => (object)[] // Empty object to prevent view errors
            ];

            $newChangedData = [
                'pop_id' => $newPopId,
                'clientsinfo' => (object)[] // Empty object to prevent view errors
            ];

            // Add billing_start_date if it was changed
            if ($billingStartDateChanged) {
                $oldChangedData['billing_start_date'] = $originalBillingStartDate;
                $newChangedData['billing_start_date'] = $client->billing_start_date;
            }

            $clientUpdateLog = new ClientEditLog();
            $clientUpdateLog->client_id = $client->id;
            $clientUpdateLog->user_id = $authUserId;
            $clientUpdateLog->old_data = json_encode($oldChangedData);
            $clientUpdateLog->new_data = json_encode($newChangedData);
            $clientUpdateLog->save();

            // Sync with Mikrotik/Radius if needed
            if (checkAPI()) {
                $sync = new SyncWithMk();
                if ($client->deleted_at == null) {
                    $sync->syncSingleClient($client->id);
                }
            } else {
                $radiusSync = new RadiusClientSync();
                if ($client->deleted_at == null) {
                    $radiusSync->syncSingleRadiusClient($client->id);
                }
            }

            DB::commit();

            return [
                'status' => 'success',
                'message' => 'POP changed successfully for client ID: ' . $client->id
            ];
        } catch (\Throwable $th) {
            DB::rollBack();

            return [
                'status' => 'error',
                'message' => 'Failed to change POP for client ID: ' . $client->id . ' - ' . $th->getMessage()
            ];
        }
    }
}

