<?php

namespace App\Services\Whatsapp;

use App\Models\WhatsappGroupMembership;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

class WhatsappMembershipService
{
    public function updateMembership(array $payload, ?int $verifiedBy = null): array
    {
        if (!Schema::hasTable('whatsapp_group_memberships')) {
            Log::error('WhatsApp membership table missing.');
            return [
                'ok' => false,
                'message' => 'Membership table missing. Please run migrations.',
            ];
        }

        $classSectionId = (int) ($payload['class_section_id'] ?? 0);
        if ($classSectionId <= 0) {
            return [
                'ok' => false,
                'message' => 'Invalid class section.',
            ];
        }

        $schoolYear = trim((string) ($payload['school_year'] ?? ''));
        $semester = trim((string) ($payload['semester'] ?? ''));
        $primaryId = (int) ($payload['primary_id'] ?? 0);
        $secondId = (int) ($payload['second_id'] ?? 0);
        $primaryMember = $payload['primary_member'] ?? null;
        $secondMember = $payload['second_member'] ?? null;

        $saved = DB::transaction(function () use (
            $classSectionId,
            $schoolYear,
            $semester,
            $primaryId,
            $secondId,
            $primaryMember,
            $secondMember,
            $verifiedBy
        ) {
            $saved = [];

            if ($primaryId > 0) {
                $id = WhatsappGroupMembership::upsertMembership(
                    $classSectionId,
                    $schoolYear,
                    $semester,
                    WhatsappGroupMembership::TYPE_PRIMARY,
                    $primaryId,
                    (bool) $primaryMember,
                    $verifiedBy
                );
                $saved[] = 'primary=' . $primaryId . ':' . ($primaryMember ? '1' : '0');
                if ($id <= 0) {
                    Log::warning('Failed to upsert primary membership.', [
                        'class_section_id' => $classSectionId,
                        'primary_id' => $primaryId,
                    ]);
                }
            }

            if ($secondId > 0) {
                $id = WhatsappGroupMembership::upsertMembership(
                    $classSectionId,
                    $schoolYear,
                    $semester,
                    WhatsappGroupMembership::TYPE_SECOND,
                    $secondId,
                    (bool) $secondMember,
                    $verifiedBy
                );
                $saved[] = 'second=' . $secondId . ':' . ($secondMember ? '1' : '0');
                if ($id <= 0) {
                    Log::warning('Failed to upsert second membership.', [
                        'class_section_id' => $classSectionId,
                        'second_id' => $secondId,
                    ]);
                }
            }

            return $saved;
        });

        if (empty($saved)) {
            return [
                'ok' => false,
                'message' => 'Nothing to save (missing parent IDs).',
            ];
        }

        return [
            'ok' => true,
            'saved' => $saved,
            'term' => [
                'school_year' => $schoolYear,
                'semester' => $semester,
            ],
        ];
    }
}
