@extends('layout.main')

@section('title', 'ভোটার এলাকা সম্পাদনা')

@section('content')
@php
    $bnMap = ['0'=>'০','1'=>'১','2'=>'২','3'=>'৩','4'=>'৪','5'=>'৫','6'=>'৬','7'=>'৭','8'=>'৮','9'=>'৯'];
@endphp

<div class="min-h-screen bg-gray-50 p-4 sm:p-6">
    <div class="max-w-3xl mx-auto">

        <div class="mb-6 flex items-center justify-between">
            <div>
                <h1 class="text-2xl font-bold text-gray-900">ভোটার এলাকা সম্পাদনা</h1>
                <p class="text-sm text-gray-600">সীট + জেলা + এলাকা তথ্য আপডেট করুন</p>
            </div>
            <a href="{{ route('voter-areas.index') }}" class="px-4 py-2 border rounded-lg hover:bg-gray-50">তালিকা</a>
        </div>

        <div class="bg-white rounded-xl shadow-sm border p-6">
            <form action="{{ route('voter-areas.update', $voterArea) }}" method="POST" class="space-y-6">
                @csrf
                @method('PUT')

                {{-- Seat --}}
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">
                        সীট <span class="text-red-500">*</span>
                    </label>
                    <select name="seat_id" required
                            class="w-full rounded-lg border px-4 py-2 bg-white focus:ring-2 focus:ring-green-500 @error('seat_id') border-red-500 @enderror">
                        <option value="">সীট নির্বাচন করুন</option>
                        @foreach($seats as $s)
                            <option value="{{ $s->id }}"
                                {{ old('seat_id', $voterArea->seat_id) == $s->id ? 'selected' : '' }}>
                                {{ $s->name }} ({{ $s->constituency }})
                            </option>
                        @endforeach
                    </select>
                    @error('seat_id')<p class="text-sm text-red-600 mt-1">{{ $message }}</p>@enderror
                </div>

                {{-- District --}}
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">
                        জেলা <span class="text-red-500">*</span>
                    </label>
                    <select id="district_id" name="district_id" required
                            class="w-full rounded-lg border px-4 py-2 bg-white focus:ring-2 focus:ring-green-500 @error('district_id') border-red-500 @enderror">
                        <option value="">জেলা নির্বাচন করুন</option>
                        @foreach($districts as $d)
                            <option value="{{ $d->id }}"
                                {{ old('district_id', $voterArea->district_id) == $d->id ? 'selected' : '' }}>
                                {{ $d->name_bn }}
                            </option>
                        @endforeach
                    </select>
                    @error('district_id')<p class="text-sm text-red-600 mt-1">{{ $message }}</p>@enderror
                </div>

                {{-- Upazila + City --}}
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">উপজেলা</label>
                        <select id="upazila_id" name="upazila_id"
                                class="w-full rounded-lg border px-4 py-2 bg-white focus:ring-2 focus:ring-green-500 @error('upazila_id') border-red-500 @enderror">
                            <option value="">(ঐচ্ছিক) উপজেলা নির্বাচন করুন</option>
                        </select>
                        @error('upazila_id')<p class="text-sm text-red-600 mt-1">{{ $message }}</p>@enderror
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">সিটি/পৌরসভা</label>
                        <select id="city_id" name="city_id"
                                class="w-full rounded-lg border px-4 py-2 bg-white focus:ring-2 focus:ring-green-500 @error('city_id') border-red-500 @enderror">
                            <option value="">(ঐচ্ছিক) সিটি/পৌরসভা নির্বাচন করুন</option>
                        </select>
                        @error('city_id')<p class="text-sm text-red-600 mt-1">{{ $message }}</p>@enderror
                    </div>
                </div>

                {{-- Ward --}}
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">ওয়ার্ড</label>
                    <select id="ward_id" name="ward_id"
                            class="w-full rounded-lg border px-4 py-2 bg-white focus:ring-2 focus:ring-green-500 @error('ward_id') border-red-500 @enderror">
                        <option value="">(ঐচ্ছিক) ওয়ার্ড নির্বাচন করুন</option>
                    </select>
                    @error('ward_id')<p class="text-sm text-red-600 mt-1">{{ $message }}</p>@enderror
                </div>

                {{-- Area Name --}}
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            এলাকার নাম (বাংলা) <span class="text-red-500">*</span>
                        </label>
                        <input type="text" name="area_name_bn"
                               value="{{ old('area_name_bn', $voterArea->area_name_bn) }}" required
                               class="w-full rounded-lg border px-4 py-2 focus:ring-2 focus:ring-green-500 @error('area_name_bn') border-red-500 @enderror">
                        @error('area_name_bn')<p class="text-sm text-red-600 mt-1">{{ $message }}</p>@enderror
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Name (English)</label>
                        <input type="text" name="area_name_en"
                               value="{{ old('area_name_en', $voterArea->area_name_en) }}"
                               class="w-full rounded-lg border px-4 py-2 focus:ring-2 focus:ring-green-500 @error('area_name_en') border-red-500 @enderror">
                        @error('area_name_en')<p class="text-sm text-red-600 mt-1">{{ $message }}</p>@enderror
                    </div>
                </div>

                {{-- Codes --}}
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">এলাকা কোড</label>
                        <input type="text" name="area_code"
                               value="{{ old('area_code', $voterArea->area_code) }}"
                               class="w-full rounded-lg border px-4 py-2 focus:ring-2 focus:ring-green-500 @error('area_code') border-red-500 @enderror">
                        @error('area_code')<p class="text-sm text-red-600 mt-1">{{ $message }}</p>@enderror
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">পোস্টাল কোড</label>
                        <input type="text" name="postal_code"
                               value="{{ old('postal_code', $voterArea->postal_code) }}"
                               class="w-full rounded-lg border px-4 py-2 focus:ring-2 focus:ring-green-500 @error('postal_code') border-red-500 @enderror">
                        @error('postal_code')<p class="text-sm text-red-600 mt-1">{{ $message }}</p>@enderror
                    </div>
                </div>

                {{-- Post Office --}}
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">পোস্ট অফিস (বাংলা)</label>
                        <input type="text" name="post_office_bn"
                               value="{{ old('post_office_bn', $voterArea->post_office_bn) }}"
                               class="w-full rounded-lg border px-4 py-2 focus:ring-2 focus:ring-green-500 @error('post_office_bn') border-red-500 @enderror">
                        @error('post_office_bn')<p class="text-sm text-red-600 mt-1">{{ $message }}</p>@enderror
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Post Office (English)</label>
                        <input type="text" name="post_office_en"
                               value="{{ old('post_office_en', $voterArea->post_office_en) }}"
                               class="w-full rounded-lg border px-4 py-2 focus:ring-2 focus:ring-green-500 @error('post_office_en') border-red-500 @enderror">
                        @error('post_office_en')<p class="text-sm text-red-600 mt-1">{{ $message }}</p>@enderror
                    </div>
                </div>

                {{-- Voters (Bangla UI + hidden numeric) --}}
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                    @php
                        $fields = [
                            'male_voters' => 'পুরুষ ভোটার',
                            'female_voters' => 'নারী ভোটার',
                            'other_voters' => 'অন্যান্য ভোটার',
                            'total_voters' => 'মোট ভোটার',
                        ];
                    @endphp

                    @foreach($fields as $k => $label)
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">{{ $label }}</label>

                            <input type="text"
                                   id="{{ $k }}_bn"
                                   inputmode="numeric"
                                   value="{{ old($k, $voterArea->$k) !== null ? strtr((string)old($k, $voterArea->$k), $bnMap) : '' }}"
                                   class="w-full rounded-lg border px-4 py-2 focus:ring-2 focus:ring-green-500 @error($k) border-red-500 @enderror">

                            <input type="hidden" name="{{ $k }}" id="{{ $k }}" value="{{ old($k, $voterArea->$k) }}">

                            @error($k)<p class="text-sm text-red-600 mt-1">{{ $message }}</p>@enderror
                        </div>
                    @endforeach
                </div>

                {{-- Status --}}
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">স্ট্যাটাস</label>
                    <select name="status"
                            class="w-full rounded-lg border px-4 py-2 bg-white focus:ring-2 focus:ring-green-500 @error('status') border-red-500 @enderror">
                        <option value="active" {{ old('status', $voterArea->status) === 'active' ? 'selected' : '' }}>সক্রিয়</option>
                        <option value="inactive" {{ old('status', $voterArea->status) === 'inactive' ? 'selected' : '' }}>নিষ্ক্রিয়</option>
                    </select>
                    @error('status')<p class="text-sm text-red-600 mt-1">{{ $message }}</p>@enderror
                </div>

                {{-- Buttons --}}
                <div class="flex justify-end gap-3 pt-4 border-t">
                    <a href="{{ route('voter-areas.index') }}"
                       class="px-5 py-2 border rounded-lg hover:bg-gray-50">বাতিল</a>

                    <button class="px-5 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700">
                        আপডেট
                    </button>
                </div>
            </form>
        </div>

    </div>
</div>

<script>
const districts = @json($districts);

function setOptions(selectEl, items, placeholder, selectedValue = "") {
    selectEl.innerHTML = '';

    const opt0 = document.createElement('option');
    opt0.value = '';
    opt0.textContent = placeholder;
    selectEl.appendChild(opt0);

    (items || []).forEach(it => {
        const opt = document.createElement('option');
        opt.value = it.id;

        // wards fallback title
        opt.textContent = it.name_bn || (it.ward_no ? ('ওয়ার্ড ' + it.ward_no) : ('#' + it.id));

        if (selectedValue !== null && selectedValue !== undefined && String(selectedValue) === String(it.id)) {
            opt.selected = true;
        }

        selectEl.appendChild(opt);
    });
}

function toBnDigits(str) {
    const map = { '0':'০','1':'১','2':'২','3':'৩','4':'৪','5':'৫','6':'৬','7':'৭','8':'৮','9':'৯' };
    return String(str).replace(/[0-9]/g, d => map[d]);
}

function toEnDigits(str) {
    const map = { '০':'0','১':'1','২':'2','৩':'3','৪':'4','৫':'5','৬':'6','৭':'7','৮':'8','৯':'9' };
    return String(str).replace(/[০-৯]/g, d => map[d]);
}

function setupBnNumber(id) {
    const visible = document.getElementById(id + '_bn');
    const hidden = document.getElementById(id);
    if (!visible || !hidden) return;

    visible.addEventListener('input', () => {
        const en = toEnDigits(visible.value).replace(/[^0-9]/g, '');
        hidden.value = en ? String(parseInt(en, 10)) : '';
        visible.value = en ? toBnDigits(en) : '';
    });
}

function refillByDistrict() {
    const districtId = document.getElementById('district_id').value;
    const d = districts.find(x => String(x.id) === String(districtId));

    const oldUpazilaId = @json(old('upazila_id', $voterArea->upazila_id));
    const oldCityId = @json(old('city_id', $voterArea->city_id));
    const oldWardId = @json(old('ward_id', $voterArea->ward_id));

    setOptions(
        document.getElementById('upazila_id'),
        d?.upazilas || [],
        '(ঐচ্ছিক) উপজেলা নির্বাচন করুন',
        oldUpazilaId || ''
    );

    setOptions(
        document.getElementById('city_id'),
        d?.cities || [],
        '(ঐচ্ছিক) সিটি/পৌরসভা নির্বাচন করুন',
        oldCityId || ''
    );

    const wardList = (d?.wards || []).map(w => ({
        id: w.id,
        name_bn: w.name_bn ? w.name_bn : ('ওয়ার্ড ' + w.ward_no),
        ward_no: w.ward_no
    }));

    setOptions(
        document.getElementById('ward_id'),
        wardList,
        '(ঐচ্ছিক) ওয়ার্ড নির্বাচন করুন',
        oldWardId || ''
    );
}

document.addEventListener('DOMContentLoaded', () => {
    ['male_voters','female_voters','other_voters','total_voters'].forEach(setupBnNumber);

    document.getElementById('district_id')?.addEventListener('change', refillByDistrict);

    // init
    refillByDistrict();
});
</script>
@endsection
