@extends('layouts.app')

@section('title', __('settings.attendance.title'))

@push('styles')
<link href="{{ asset('css/stage-academy.css') }}" rel="stylesheet">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
<style>
    #attendanceMap {
        height: 380px;
        border-radius: 14px;
        overflow: hidden;
        border: 1px solid rgba(0, 0, 0, 0.08);
    }
    .dark-mode #attendanceMap {
        border-color: rgba(255, 255, 255, 0.12);
    }
    .attendance-geolocate-control {
        background: #fff;
        border: 1px solid rgba(0, 0, 0, 0.12);
        border-radius: 8px;
        width: 38px;
        height: 38px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        color: #0d6efd;
        box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
    }
    .attendance-geolocate-control:hover {
        background: #f8f9fa;
    }
    .attendance-geolocate-control:disabled {
        opacity: 0.65;
        cursor: wait;
    }
    body.dark-mode .attendance-geolocate-control {
        background: #1e293b;
        border-color: rgba(255, 255, 255, 0.15);
        color: #8ab4ff;
    }
    body.dark-mode .attendance-geolocate-control:hover {
        background: #0f172a;
    }
</style>
@endpush

@section('content')
<div class="container-fluid">
    <div class="d-flex align-items-center justify-content-between gap-3 mb-4">
        <div class="flex-grow-1">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-1">
                    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">{{ __('dashboard') }}</a></li>
                    <li class="breadcrumb-item"><a href="{{ route('settings') }}">{{ __('settings') }}</a></li>
                    <li class="breadcrumb-item active" aria-current="page">{{ __('settings.attendance.title') }}</li>
                </ol>
            </nav>
            <h4 class="fw-bold mb-0">{{ __('settings.attendance.title') }}</h4>
            <div class="text-muted small">{{ __('settings.attendance.subtitle') }}</div>
        </div>
        <a href="{{ route('settings') }}" class="btn btn-outline-secondary app-back-end">
            <i class="bi bi-arrow-{{ app()->getLocale() == 'ar' ? 'right' : 'left' }}"></i> {{ __('common.back') }}
        </a>
    </div>

    @if(session('success'))
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            {{ session('success') }}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    @endif
    @if($errors->any())
        <div class="alert alert-danger">
            <ul class="mb-0">
                @foreach($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <div class="card sa-card border-0">
        <div class="card-body">
            <form method="POST" action="{{ route('settings.attendance-settings.store') }}">
                @csrf
                <div class="row g-3">
                    <div class="col-12">
                        <div class="fw-bold mb-1">{{ __('settings.attendance.location_card_title') }}</div>
                        <div class="text-muted small">{{ __('settings.attendance.location_card_desc') }}</div>
                    </div>

                    <div class="col-12">
                        <div class="d-flex align-items-center justify-content-between gap-3">
                            <div class="fw-bold">{{ __('settings.attendance.select_location') }}</div>
                            <div class="text-muted small">{{ __('settings.attendance.map_hint') }}</div>
                        </div>
                        <div class="mt-2" id="attendanceMap"></div>
                    </div>

                    <div class="col-12 col-md-6">
                        <label class="form-label">{{ __('settings.attendance.latitude') }}</label>
                        <input type="text" name="latitude" id="attendanceLatitude" class="form-control" value="{{ old('latitude', $settings?->latitude) }}" dir="ltr" readonly>
                    </div>

                    <div class="col-12 col-md-6">
                        <label class="form-label">{{ __('settings.attendance.longitude') }}</label>
                        <input type="text" name="longitude" id="attendanceLongitude" class="form-control" value="{{ old('longitude', $settings?->longitude) }}" dir="ltr" readonly>
                    </div>

                    <div class="col-12 col-md-6">
                        <label class="form-label">{{ __('settings.attendance.allowed_radius') }}</label>
                        <input type="number" name="allowed_radius" id="attendanceAllowedRadius" class="form-control" value="{{ old('allowed_radius', $settings?->allowed_radius ?? 50) }}" min="1" dir="ltr">
                    </div>

                    <div class="col-12">
                        <hr class="my-2">
                        <div class="fw-bold mb-1">إعدادات الخصومات</div>
                        <div class="text-muted small">تُستخدم لاحتساب خصم التأخير والغياب والإجازة غير المدفوعة من الراتب الاسمي</div>
                    </div>

                    <div class="col-12 col-md-6">
                        <label class="form-label">سعر دقيقة التأخير</label>
                        <input type="number" name="late_minute_price" class="form-control" value="{{ old('late_minute_price', $settings?->late_minute_price ?? 0) }}" min="0" step="1" dir="ltr">
                    </div>

                    <div class="col-12 col-md-6">
                        <label class="form-label">خصم الغياب (عدد أيام من الراتب الاسمي)</label>
                        <select name="absence_deduction_days" class="form-select">
                            @php($absenceDays = (int) old('absence_deduction_days', $settings?->absence_deduction_days ?? 2))
                            <option value="1" @selected($absenceDays === 1)>يوم واحد</option>
                            <option value="2" @selected($absenceDays === 2)>يومان</option>
                            <option value="3" @selected($absenceDays === 3)>3 أيام</option>
                        </select>
                    </div>

                    <div class="col-12 col-md-6">
                        <label class="form-label">خصم الإجازة غير المدفوعة (عدد أيام من الراتب الاسمي)</label>
                        <select name="unpaid_leave_deduction_days" class="form-select">
                            @php($unpaidDays = (int) old('unpaid_leave_deduction_days', $settings?->unpaid_leave_deduction_days ?? 1))
                            <option value="1" @selected($unpaidDays === 1)>يوم واحد</option>
                            <option value="2" @selected($unpaidDays === 2)>يومان</option>
                            <option value="3" @selected($unpaidDays === 3)>3 أيام</option>
                        </select>
                    </div>

                    <div class="col-12 col-md-6">
                        <label class="form-label">خصم عدم تسجيل الخروج (مبلغ ثابت)</label>
                        <input type="number" name="missing_checkout_penalty_amount" class="form-control" value="{{ old('missing_checkout_penalty_amount', $settings?->missing_checkout_penalty_amount ?? 0) }}" min="0" step="1" dir="ltr">
                    </div>

                    <div class="col-12 d-flex justify-content-end">
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-save me-1"></i> {{ __('settings.attendance.save') }}
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', () => {
        const latitudeInput = document.getElementById('attendanceLatitude');
        const longitudeInput = document.getElementById('attendanceLongitude');
        const radiusInput = document.getElementById('attendanceAllowedRadius');
        const i18n = {
            useCurrentLocation: `{{ __('settings.attendance.use_current_location') }}`,
            locating: `{{ __('settings.attendance.locating') }}`,
            geolocationNotSupported: `{{ __('settings.attendance.geolocation_not_supported') }}`,
            locationFetchFailed: `{{ __('settings.attendance.location_fetch_failed') }}`,
        };

        const savedLat = parseFloat(latitudeInput?.value ?? '');
        const savedLng = parseFloat(longitudeInput?.value ?? '');

        const hasSaved = Number.isFinite(savedLat) && Number.isFinite(savedLng);
        const defaultCenter = { lat: 33.3152, lng: 44.3661 };
        const center = hasSaved ? { lat: savedLat, lng: savedLng } : defaultCenter;

        const map = L.map('attendanceMap', { zoomControl: true }).setView([center.lat, center.lng], hasSaved ? 17 : 13);
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 19,
            attribution: '&copy; OpenStreetMap'
        }).addTo(map);

        const marker = L.marker([center.lat, center.lng], { draggable: true }).addTo(map);

        const getRadiusMeters = () => {
            const raw = radiusInput ? parseInt(radiusInput.value, 10) : NaN;
            if (Number.isFinite(raw) && raw > 0) return raw;
            return 50;
        };

        const radiusCircle = L.circle([center.lat, center.lng], {
            radius: getRadiusMeters(),
            color: '#0d6efd',
            weight: 2,
            fillColor: '#0d6efd',
            fillOpacity: 0.15,
            interactive: false,
        }).addTo(map);

        const setInputsFromLatLng = (latlng) => {
            if (!latlng) return;
            latitudeInput.value = Number(latlng.lat).toFixed(7);
            longitudeInput.value = Number(latlng.lng).toFixed(7);
        };

        const syncRadiusCircle = () => {
            const pos = marker.getLatLng();
            radiusCircle.setLatLng(pos);
            radiusCircle.setRadius(getRadiusMeters());
        };

        if (hasSaved) {
            setInputsFromLatLng({ lat: savedLat, lng: savedLng });
        }
        syncRadiusCircle();

        map.on('click', (e) => {
            marker.setLatLng(e.latlng);
            setInputsFromLatLng(e.latlng);
            syncRadiusCircle();
        });

        marker.on('dragend', () => {
            const pos = marker.getLatLng();
            setInputsFromLatLng(pos);
            syncRadiusCircle();
        });

        if (radiusInput) {
            radiusInput.addEventListener('input', () => {
                syncRadiusCircle();
            });
            radiusInput.addEventListener('change', () => {
                syncRadiusCircle();
            });
        }

        const GeoLocateControl = L.Control.extend({
            options: {
                position: 'topright'
            },
            onAdd() {
                const container = L.DomUtil.create('div', 'leaflet-bar');
                const button = L.DomUtil.create('button', 'attendance-geolocate-control', container);
                button.type = 'button';
                button.title = i18n.useCurrentLocation;
                button.setAttribute('aria-label', i18n.useCurrentLocation);
                button.innerHTML = '<i class="bi bi-crosshair2"></i>';

                L.DomEvent.disableClickPropagation(container);
                L.DomEvent.on(button, 'click', (event) => {
                    L.DomEvent.preventDefault(event);
                    if (!navigator.geolocation) {
                        window.alert(i18n.geolocationNotSupported);
                        return;
                    }

                    button.disabled = true;
                    const previousTitle = button.title;
                    button.title = i18n.locating;

                    navigator.geolocation.getCurrentPosition(
                        (position) => {
                            const nextLatLng = {
                                lat: position.coords.latitude,
                                lng: position.coords.longitude,
                            };

                            marker.setLatLng(nextLatLng);
                            map.setView([nextLatLng.lat, nextLatLng.lng], 17);
                            setInputsFromLatLng(nextLatLng);
                            syncRadiusCircle();

                            button.disabled = false;
                            button.title = previousTitle;
                        },
                        () => {
                            button.disabled = false;
                            button.title = previousTitle;
                            window.alert(i18n.locationFetchFailed);
                        },
                        {
                            enableHighAccuracy: true,
                            timeout: 10000,
                            maximumAge: 0,
                        }
                    );
                });

                return container;
            }
        });

        map.addControl(new GeoLocateControl());
    });
</script>
@endpush
