@extends('layouts.aura-main')

@section('main-content')
<div class="max-w-7xl mx-auto pb-20 px-4" x-data="periodManager()">
    
    {{-- Check for SILENT validation errors --}}
@if ($errors->any())
    <div class="mb-6 p-4 bg-orange-50 border-l-4 border-orange-500 text-orange-900 shadow-md">
        <div class="flex items-center mb-2">
            <i class="fas fa-shield-alt mr-2"></i>
            <span class="text-xs font-black uppercase">Validation Request Denied</span>
        </div>
        <ul class="list-disc list-inside text-[11px] font-bold">
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
    
    {{-- Header Section --}}
{{-- Header Section --}}
<div class="flex justify-between items-end mb-8 border-b border-slate-900 pb-4">
    <div>
        <h1 class="text-3xl font-black text-slate-900">Payroll Periods</h1>
        <p class="text-[10px] font-bold text-slate-400 mt-1">
            Active year: {{ $currentFinancialYear->year ?? 'Not set' }} 
        </p>
    </div>

    <div class="flex gap-3">
        <button @click="openGenerateModal()" class="bg-emerald-600 text-white px-6 py-2.5 text-[10px] font-black hover:bg-emerald-700 transition shadow-lg">
            <i class="fas fa-calendar-plus mr-2"></i> Auto-generate months
        </button>
        <button @click="openCreateModal()" class="bg-slate-900 text-white px-6 py-2.5 text-[10px] font-black hover:bg-slate-800 transition shadow-lg">
            <i class="fas fa-plus mr-2"></i> Create manual period
        </button>
    </div>
</div>



{{-- MODAL: Auto-Generate Months --}}
<div x-show="generateModalOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm" x-cloak>
    <div class="bg-white rounded-sm shadow-2xl w-full max-w-lg overflow-hidden" @click.away="generateModalOpen = false">
        <div class="p-6 border-b border-slate-100 flex justify-between items-center bg-slate-50">
            <h3 class="text-sm font-black text-slate-900">Bulk generate payroll periods</h3>
            <button @click="generateModalOpen = false" class="text-slate-400 hover:text-slate-900"><i class="fas fa-times"></i></button>
        </div>
        
        <form action="{{ route('payroll.periods.generate') }}" method="POST" class="p-8">
            @csrf
            <div class="space-y-5">
                <div class="p-4 bg-emerald-50 border border-emerald-100 rounded text-[11px] text-emerald-700 font-medium">
                    <i class="fas fa-info-circle mr-1"></i> This will automatically create 12 monthly payroll periods based on the dates selected below.
                </div>

                <div>
                    <label class="block text-[10px] font-black text-slate-500 mb-1">Select financial year</label>
                    <select name="financial_year_id" x-model="generateData.financial_year_id" @change="updateGenerateDates" class="quickbooks-input font-bold" required>
                        <option value="">Select a year</option>
                        @foreach($financialYears as $fy)
                            <option value="{{ $fy->id }}" 
                                    data-start="{{ $fy->start_date->format('Y-m-d') }}" 
                                    data-end="{{ $fy->end_date->format('Y-m-d') }}">
                                {{ $fy->year }}
                            </option>
                        @endforeach
                    </select>
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-[10px] font-black text-slate-500 mb-1">Cycle start date</label>
                        <input type="date" name="start_date" x-model="generateData.start_date" class="quickbooks-input" required>
                    </div>
                    <div>
                        <label class="block text-[10px] font-black text-slate-500 mb-1">Cycle end date</label>
                        <input type="date" name="end_date" x-model="generateData.end_date" class="quickbooks-input" required>
                    </div>
                </div>
            </div>

            <div class="mt-10 flex justify-end gap-3">
                <button type="button" @click="generateModalOpen = false" class="px-6 py-2.5 text-[10px] font-black text-slate-500 hover:bg-slate-50 transition">Cancel</button>
                <button type="submit" class="bg-emerald-600 text-white px-10 py-2.5 text-[10px] font-black shadow-lg">Generate all months</button>
            </div>
        </form>
    </div>
</div>
   
   
   {{-- Filter Bar --}}
<div class="bg-slate-50 border border-slate-200 p-4 mb-6 rounded-sm">
    <form action="{{ route('payroll.periods.index') }}" method="GET" class="flex flex-wrap items-end gap-4">
        {{-- Year Filter --}}
        <div class="w-48">
            <label class="block text-[10px] font-black text-slate-500 mb-1">Filter by Year</label>
            <select name="financial_year_id" class="quickbooks-input bg-white font-bold" onchange="this.form.submit()">
                <option value="">All Financial Years</option>
                @foreach($financialYears as $fy)
                    <option value="{{ $fy->id }}" {{ request('financial_year_id') == $fy->id ? 'selected' : '' }}>
                        {{ $fy->year }}
                    </option>
                @endforeach
            </select>
        </div>

        {{-- Status Filter --}}
        <div class="w-48">
            <label class="block text-[10px] font-black text-slate-500 mb-1">Filter by Status</label>
            <select name="status" class="quickbooks-input bg-white font-bold" onchange="this.form.submit()">
                <option value="">All Statuses</option>
                <option value="open" {{ request('status') == 'open' ? 'selected' : '' }}>Open</option>
                <option value="closed" {{ request('status') == 'closed' ? 'selected' : '' }}>Closed</option>
                <option value="processing" {{ request('status') == 'processing' ? 'selected' : '' }}>Processing</option>
            </select>
        </div>

        {{-- Reset Button --}}
        <div class="flex-1 flex justify-end">
            @if(request('financial_year_id') || request('status'))
                <a href="{{ route('payroll.periods.index') }}" class="text-[10px] font-black text-red-600 hover:text-red-800 transition py-2 px-4 uppercase">
                    <i class="fas fa-times-circle mr-1"></i> Clear Filters
                </a>
            @endif
        </div>
    </form>
</div>

    {{-- Periods Table --}}
    <div class="bg-white border border-slate-200 rounded-sm overflow-hidden shadow-sm">
        <table class="w-full text-left border-collapse">
            <thead>
                <tr class="bg-slate-50 border-b border-slate-200">
                    <th class="px-6 py-3 text-[10px] font-black text-slate-500">Period name</th>
                    <th class="px-6 py-3 text-[10px] font-black text-slate-500">Date range</th>
                    <th class="px-6 py-3 text-[10px] font-black text-slate-500 text-right">Cutoff date</th>
                    <th class="px-6 py-3 text-[10px] font-black text-slate-500 text-right">Payment date</th>
                    <th class="px-6 py-3 text-[10px] font-black text-slate-500 text-center">Status</th>
                    <th class="px-6 py-3 text-[10px] font-black text-slate-500 text-right">Actions</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-100">
                @forelse($payrollPeriods as $period)
                <tr class="hover:bg-slate-50 transition-colors">
                    <td class="px-6 py-4">
                        <div class="text-xs font-black text-slate-900">{{ $period->period_name }}</div>
                        <div class="text-[9px] text-slate-400 font-bold">{{ $period->month_name }}</div>
                    </td>
                    <td class="px-6 py-4 text-xs text-slate-600 font-medium">
                        {{ \Carbon\Carbon::parse($period->start_date)->format('d M') }} - {{ \Carbon\Carbon::parse($period->end_date)->format('d M, Y') }}
                    </td>
                    <td class="px-6 py-4 text-xs text-slate-600 text-right">{{ \Carbon\Carbon::parse($period->cutoff_date)->format('d M, Y') }}</td>
                    <td class="px-6 py-4 text-xs text-slate-600 text-right">{{ \Carbon\Carbon::parse($period->payment_date)->format('d M, Y') }}</td>
                    <td class="px-6 py-4 text-center">
                        <span class="px-2 py-1 text-[9px] font-black rounded-full 
                            {{ $period->status === 'open' ? 'bg-blue-100 text-blue-700' : ($period->status === 'closed' ? 'bg-slate-100 text-slate-400' : 'bg-amber-100 text-amber-700') }}">
                            {{ ucfirst($period->status) }}
                        </span>
                    </td>
                    <td class="px-6 py-4 text-right">
                        <div class="flex justify-end gap-3">
                            <button @click="openEditModal({{ json_encode($period) }})" class="text-slate-400 hover:text-slate-900 transition"><i class="fas fa-edit"></i></button>
                            
                            @if($period->status === 'open')
                                <form action="{{ route('payroll.periods.close', $period->id) }}" method="POST" class="inline">
                                    @csrf
                                    <button type="submit" class="text-slate-400 hover:text-red-600" title="Close period"><i class="fas fa-lock"></i></button>
                                </form>
                            @else
                                <form action="{{ route('payroll.periods.reopen', $period->id) }}" method="POST" class="inline">
                                    @csrf
                                    <button type="submit" class="text-slate-400 hover:text-emerald-600" title="Reopen period"><i class="fas fa-unlock"></i></button>
                                </form>
                            @endif

                            <form action="{{ route('payroll.periods.destroy', $period->id) }}" method="POST" class="inline" onsubmit="return confirm('Delete this period?')">
                                @csrf @method('DELETE')
                                <button type="submit" class="text-slate-300 hover:text-red-500"><i class="fas fa-trash"></i></button>
                            </form>
                        </div>
                    </td>
                </tr>
                @empty
                <tr>
                    <td colspan="6" class="px-6 py-20 text-center text-xs text-slate-400 italic font-medium">No payroll periods found for this year.</td>
                </tr>
                @endforelse
            </tbody>
        </table>
    </div>

    {{-- MODAL: Create/Edit --}}
    <div x-show="modalOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm" x-cloak>
        <div class="bg-white rounded-sm shadow-2xl w-full max-w-lg overflow-hidden" @click.away="modalOpen = false">
            <div class="p-6 border-b border-slate-100 flex justify-between items-center bg-slate-50">
                <h3 class="text-sm font-black text-slate-900" x-text="isEdit ? 'Edit payroll period' : 'New payroll period'"></h3>
                <button @click="modalOpen = false" class="text-slate-400 hover:text-slate-900"><i class="fas fa-times"></i></button>
            </div>
            
            <form :action="formAction" method="POST" class="p-8">
                @csrf
                <template x-if="isEdit">@method('PUT')</template>
                
                <div class="space-y-5">
                    {{-- Financial Year Selection --}}
                 {{-- Financial Year Selection --}}
<div>
    <label class="block text-[10px] font-black text-slate-500 mb-1">Financial year</label>
    <select name="financial_year_id" x-model="formData.financial_year_id" class="quickbooks-input font-bold" required>
        <option value="">Select a year</option>
        @foreach($financialYears as $fy)
            <option value="{{ $fy->id }}">{{ $fy->year }} ({{ $fy->start_date->format('M Y') }} - {{ $fy->end_date->format('M Y') }})</option>
        @endforeach
    </select>
</div>
                    <div>
                        <label class="block text-[10px] font-black text-slate-500 mb-1">Period name</label>
                        <input type="text" name="period_name" x-model="formData.period_name" class="quickbooks-input font-bold" placeholder="e.g. April 2026 Payroll" required>
                    </div>

                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-[10px] font-black text-slate-500 mb-1">Start date</label>
                            <input type="date" name="start_date" x-model="formData.start_date" class="quickbooks-input" required>
                        </div>
                        <div>
                            <label class="block text-[10px] font-black text-slate-500 mb-1">End date</label>
                            <input type="date" name="end_date" x-model="formData.end_date" class="quickbooks-input" required>
                        </div>
                    </div>

                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-[10px] font-black text-slate-500 mb-1 text-blue-600">Cutoff date</label>
                            <input type="date" name="cutoff_date" x-model="formData.cutoff_date" class="quickbooks-input border-blue-200" required>
                        </div>
                        <div>
                            <label class="block text-[10px] font-black text-slate-500 mb-1 text-emerald-600">Payment date</label>
                            <input type="date" name="payment_date" x-model="formData.payment_date" class="quickbooks-input border-emerald-200" required>
                        </div>
                    </div>

                    <template x-if="isEdit">
                        <div>
                            <label class="block text-[10px] font-black text-slate-500 mb-1">Status</label>
                            <select name="status" x-model="formData.status" class="quickbooks-input font-bold">
                                <option value="open">Open</option>
                                <option value="closed">Closed</option>
                                <option value="processing">Processing</option>
                            </select>
                        </div>
                    </template>
                </div>

                <div class="mt-10 flex justify-end gap-3">
                    <button type="button" @click="modalOpen = false" class="px-6 py-2.5 text-[10px] font-black text-slate-500 hover:bg-slate-50 transition">Cancel</button>
                    <button type="submit" class="bg-slate-900 text-white px-10 py-2.5 text-[10px] font-black shadow-lg shadow-slate-200" x-text="isEdit ? 'Update period' : 'Create period'"></button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>

   function periodManager() {
    return {
        modalOpen: false,
        generateModalOpen: false,
        isEdit: false,
        formAction: "{{ route('payroll.periods.store') }}",
        formData: { financial_year_id: '', period_name: '', start_date: '', end_date: '', cutoff_date: '', payment_date: '', status: 'open' },
        
        // Data for the generate modal
        generateData: { financial_year_id: '', start_date: '', end_date: '' },

        openGenerateModal() {
            this.generateModalOpen = true;
            // Default to current active year if available
            if('{{ $currentFinancialYear->id ?? "" }}') {
                this.generateData.financial_year_id = '{{ $currentFinancialYear->id ?? "" }}';
                this.generateData.start_date = '{{ $currentFinancialYear->start_date->format("Y-m-d") ?? "" }}';
                this.generateData.end_date = '{{ $currentFinancialYear->end_date->format("Y-m-d") ?? "" }}';
            }
        },

        updateGenerateDates(e) {
            const selectedOption = e.target.options[e.target.selectedIndex];
            this.generateData.start_date = selectedOption.getAttribute('data-start');
            this.generateData.end_date = selectedOption.getAttribute('data-end');
        },

        openCreateModal() {
            this.isEdit = false;
            this.formData = { financial_year_id: '{{ $currentFinancialYear->id ?? "" }}', period_name: '', start_date: '', end_date: '', cutoff_date: '', payment_date: '', status: 'open' };
            this.formAction = "{{ route('payroll.periods.store') }}";
            this.modalOpen = true;
        },

        openEditModal(period) {
            this.isEdit = true;
            this.formData = { ...period };
            this.formAction = `/payroll/periods/${period.id}`;
            this.modalOpen = true;
        }
    }
}
</script>

<style>
    .quickbooks-input { border: 1px solid #e2e8f0; border-radius: 2px; padding: 10px; font-size: 13px; width: 100%; transition: border-color 0.2s; }
    .quickbooks-input:focus { outline: none; border-color: #000; }
    [x-cloak] { display: none !important; }
</style>
@endsection