@extends('layouts.app')
@section('title', 'Period Closing')

@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
    <li class="breadcrumb-item active">Period Closing</li>
@endsection

@section('content')
<div class="page-header">
    <div>
        <h1 class="page-title">Close the Books</h1>
        <p class="page-subtitle">QuickBooks-style year-end closing — no closing journal entries required</p>
    </div>
</div>

@if(session('success'))
<div class="alert alert-success alert-dismissible d-flex gap-2 mb-4">
    <i class="bi bi-check-circle flex-shrink-0"></i><div>{{ session('success') }}</div>
    <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert"></button>
</div>
@endif

@if($errors->any())
<div class="alert alert-danger alert-dismissible mb-4">
    @foreach($errors->all() as $error)<div>{{ $error }}</div>@endforeach
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
@endif

<div class="row g-4 mb-4">
    <div class="col-12 col-xl-7">
        <div class="card h-100">
            <div class="card-header"><i class="bi bi-calendar-x me-2 text-primary"></i>Books Closing Date</div>
            <div class="card-body">
                <p class="text-muted mb-4" style="font-size:13.5px">
                    Set the date through which your books are closed. Transactions dated on or before this date
                    cannot be added or changed unless the closing password is entered — just like QuickBooks.
                </p>

                @if(auth()->user()->hasPermission('settings','edit'))
                <form method="POST" action="{{ route('admin.fiscal-years.update-closing') }}">
                    @csrf @method('PUT')
                    <div class="row g-3">
                        <div class="col-12 col-md-6">
                            <label class="form-label fw-semibold">Closing Date</label>
                            <input type="date" name="books_closing_date" class="form-control"
                                   value="{{ old('books_closing_date', optional($closingDate)->format('Y-m-d')) }}">
                            <div class="form-text">
                                Leave blank to open all periods. Suggested:
                                @if($suggestedClosingDate)
                                    <button type="button" class="btn btn-link btn-sm p-0 align-baseline"
                                            onclick="document.querySelector('[name=books_closing_date]').value='{{ $suggestedClosingDate->format('Y-m-d') }}'">
                                        {{ $suggestedClosingDate->format('d M Y') }}
                                    </button>
                                @else
                                    last completed fiscal year end
                                @endif
                            </div>
                        </div>
                        <div class="col-12 col-md-6">
                            <label class="form-label fw-semibold">Closing Password <span class="text-muted fw-normal">(optional)</span></label>
                            <input type="password" name="closing_password" class="form-control" autocomplete="new-password"
                                   placeholder="{{ $hasClosingPassword ? 'Enter new password to change' : 'Optional password for closed periods' }}">
                            <input type="password" name="closing_password_confirmation" class="form-control mt-2" autocomplete="new-password"
                                   placeholder="Confirm password">
                            @if($hasClosingPassword)
                            <div class="form-check mt-2">
                                <input class="form-check-input" type="checkbox" name="remove_closing_password" value="1" id="removeClosingPassword">
                                <label class="form-check-label" for="removeClosingPassword">Remove closing password</label>
                            </div>
                            @endif
                        </div>
                        <div class="col-12">
                            <button type="submit" class="btn btn-primary">
                                <i class="bi bi-save me-1"></i>Save Closing Settings
                            </button>
                        </div>
                    </div>
                </form>
                @else
                <div class="p-3 rounded-2 border bg-light">
                    @if($closingDate)
                        <strong>Current closing date:</strong> {{ $closingDate->format('d M Y') }}
                    @else
                        <span class="text-muted">No closing date set — all periods are open.</span>
                    @endif
                </div>
                @endif
            </div>
        </div>
    </div>

    <div class="col-12 col-xl-5">
        <div class="card h-100">
            <div class="card-header"><i class="bi bi-list-check me-2 text-primary"></i>QuickBooks-Style Closing Steps</div>
            <div class="card-body" style="font-size:13.5px">
                <ol class="mb-0 ps-3">
                    <li class="mb-2">Run your <strong>Profit &amp; Loss</strong> and <strong>Balance Sheet</strong> reports for the year you are closing.</li>
                    <li class="mb-2">Set the <strong>Closing Date</strong> to the last day of that fiscal year.</li>
                    <li class="mb-2">Optionally set a <strong>password</strong> so only authorized users can change closed-period transactions.</li>
                    <li>No closing journal entry is needed — net income rolls to <strong>Retained Earnings</strong> automatically on reports.</li>
                </ol>
            </div>
        </div>
    </div>
</div>

@if($closingDate)
<div class="alert alert-warning d-flex align-items-center gap-2 mb-4" style="font-size:13.5px">
    <i class="bi bi-lock-fill fs-5"></i>
    <div>
        <strong>Books are closed through {{ $closingDate->format('d M Y') }}.</strong>
        Transactions on or before this date are protected.
    </div>
</div>
@endif

@if($currentYear)
<div class="alert alert-success d-flex align-items-center gap-2 mb-4" style="font-size:13.5px">
    <i class="bi bi-calendar-check fs-5"></i>
    <div>
        <strong>Current Period:</strong> {{ $currentYear->name }}
        &mdash; {{ $currentYear->start_date->format('d M Y') }} to {{ $currentYear->end_date->format('d M Y') }}
    </div>
</div>
@endif

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <span><i class="bi bi-calendar3 me-2 text-primary"></i>Accounting Periods</span>
        <span class="text-muted small">Created automatically — no annual setup required</span>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead>
                    <tr>
                        <th>Period</th>
                        <th>Start Date</th>
                        <th>End Date</th>
                        <th>Status</th>
                        <th style="width:100px">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($fiscalYears as $fy)
                    <tr class="{{ $fy->is_current ? 'table-success' : '' }}">
                        <td class="fw-semibold">
                            {{ $fy->name }}
                            @if($fy->is_current)
                                <span class="badge ms-1" style="background:#d1e7dd;color:#0a3622">Current</span>
                            @endif
                        </td>
                        <td>{{ $fy->start_date->format('d M Y') }}</td>
                        <td>{{ $fy->end_date->format('d M Y') }}</td>
                        <td>
                            @php
                                $statusStyles = ['open'=>'#d1e7dd|#0a3622','locked'=>'#f8d7da|#842029','closed'=>'#e9ecef|#495057'];
                                [$bg,$fg] = explode('|', $statusStyles[$fy->status] ?? '#e9ecef|#495057');
                            @endphp
                            <span class="badge" style="background:{{ $bg }};color:{{ $fg }}">
                                {{ $fy->status === 'locked' ? 'Closed' : ucfirst($fy->status) }}
                            </span>
                        </td>
                        <td>
                            @if($fy->status !== 'locked' && auth()->user()->hasPermission('settings','edit'))
                            <form method="POST" action="{{ route('admin.fiscal-years.lock', $fy) }}" id="lock-{{ $fy->id }}">
                                @csrf @method('PATCH')
                                <button type="button" class="btn btn-outline-warning btn-sm"
                                    data-confirm data-form="#lock-{{ $fy->id }}"
                                    data-confirm-title="Close This Period?"
                                    data-confirm-text="Lock '{{ $fy->name }}'? No new transactions can be posted to this period."
                                    data-confirm-icon="warning"
                                    data-confirm-color="#E67E22"
                                    data-confirm-btn="Close Period"
                                    title="Close Period">
                                    <i class="bi bi-lock"></i>
                                </button>
                            </form>
                            @endif
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="5" class="text-center py-5">
                            <i class="bi bi-calendar display-6 d-block text-muted mb-2"></i>
                            <span class="text-muted">No periods yet. They appear automatically when you post your first transaction.</span>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="card mt-4">
    <div class="card-header"><i class="bi bi-info-circle me-2 text-primary"></i>How Virtual Closing Works</div>
    <div class="card-body" style="font-size:13.5px">
        <div class="row g-3">
            <div class="col-12 col-md-4">
                <div class="d-flex gap-2">
                    <i class="bi bi-check-circle text-success fs-5 mt-1 flex-shrink-0"></i>
                    <div><strong>No Closing Entries</strong><br><span class="text-muted">Income and expense accounts reset on reports at year-end using date filters — no manual closing journal is posted.</span></div>
                </div>
            </div>
            <div class="col-12 col-md-4">
                <div class="d-flex gap-2">
                    <i class="bi bi-shield-check text-primary fs-5 mt-1 flex-shrink-0"></i>
                    <div><strong>Retained Earnings</strong><br><span class="text-muted">Prior-year net profit or loss is calculated automatically and shown as Retained Earnings on the Balance Sheet.</span></div>
                </div>
            </div>
            <div class="col-12 col-md-4">
                <div class="d-flex gap-2">
                    <i class="bi bi-lock text-warning fs-5 mt-1 flex-shrink-0"></i>
                    <div><strong>Closing Date Protection</strong><br><span class="text-muted">Once set, the closing date prevents accidental changes to finalized periods — matching QuickBooks behaviour.</span></div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
