@php
    $layout = auth()->user()->role === 'super_admin' ? 'layouts.admin' : 'component2.layouts.app';
@endphp

@extends($layout)

@section('title', isset($beneficiary) ? 'Edit SeedLab Beneficiary' : 'Register New SeedLab Beneficiary')

@section('content')
<div class="container-fluid py-4">
    <!-- Dashboard Header -->
    <div class="dashboard-header">
        <div class="container-fluid">
            <div class="row align-items-center dashboard-header-content">
                <div class="col-lg-6">
                    <h1 class="dashboard-title">
                        <i class="fas fa-tachometer-alt" style="color: var(--dhis2-blue-primary);"></i>
                        SeedLab Beneficiaries Registration
                    </h1>
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="javascript:history.back()">Back</a></li>
                            <li class="breadcrumb-item"><a href="{{ route('component2.dashboard') }}">Component 2 Dashboard</a></li>
                            <li class="breadcrumb-item active">SeedLab Beneficiaries</li>
                        </ol>
                    </nav>
                </div>
                <div class="col-lg-6">
                    <div class="d-flex justify-content-lg-end gap-2 dashboard-actions">
                        
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="row justify-content-center">
        <div class="col-12 col-lg-11">
            <div class="card shadow-sm">
                <div class="card-header bg-success text-white">
                    <h4 class="mb-0">
                        <i class="fas fa-seedling"></i>
                        {{ isset($beneficiary) ? 'Edit SeedLab Beneficiary' : 'Register New SeedLab Beneficiary' }}
                    </h4>
                </div>

                <div class="card-body">
                    <form action="{{ isset($beneficiary) ? route('component2.seedlab.update', $beneficiary) : route('component2.seedlab.store') }}"
                          method="POST" id="seedlabForm">
                        @csrf
                        @if(isset($beneficiary)) @method('PUT') @endif

                        <!-- BASIC INFO -->
                        <h5 class="mt-4 text-primary">Basic Information</h5>
                        <hr>

                        <div class="row g-3">
                            <div class="col-md-2">
                                <label class="form-label">SN <span class="text-danger">*</span></label>
                                <input type="number" name="sn" class="form-control @error('sn') is-invalid @enderror"
                                       value="{{ old('sn', $beneficiary->sn ?? '') }}" required>
                                @error('sn') <div class="invalid-feedback">{{ $message }}</div> @enderror
                            </div>

                            <div class="col-md-6">
                                <label class="form-label">Full Name <span class="text-danger">*</span></label>
                                <input type="text" name="full_name" class="form-control @error('full_name') is-invalid @enderror"
                                       value="{{ old('full_name', $beneficiary->full_name ?? '') }}" required>
                                @error('full_name') <div class="invalid-feedback">{{ $message }}</div> @enderror
                            </div>

                            <div class="col-md-4">
                                <label class="form-label">Business Sector <span class="text-danger">*</span></label>
                                <select name="business_sector" class="form-select @error('business_sector') is-invalid @enderror" required>
                                    <option value="">Select sector</option>
                                    @foreach(['Agriculture','Education','Healthcare','Real Estate','Services','Supply & Trading','Hospitality','Construction','Automobile', 'Electronics', 'Fashion Design', 'ICT', 'Media & Entertainment', 'Tourism'] as $s)
                                        <option value="{{ $s }}" {{ old('business_sector', $beneficiary->business_sector ?? '') === $s ? 'selected' : '' }}>
                                            {{ $s }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                        <div class="row g-3 mt-3">
                            <div class="col-md-3">
                                <label class="form-label">Cohort <span class="text-danger">*</span></label>
                                <select name="cohort" class="form-select @error('cohort') is-invalid @enderror" required>
                                    <option value="">-- Select Cohort --</option>
                                    <option value="1" {{ old('cohort', $beneficiary->cohort ?? '') === '1' ? 'selected' : '' }}>1</option>
                                    <option value="2" {{ old('cohort', $beneficiary->cohort ?? '') === '2' ? 'selected' : '' }}>2</option>
                                </select>
                                @error('cohort') <div class="invalid-feedback">{{ $message }}</div> @enderror
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Year <span class="text-danger">*</span></label>
                                <select name="cohort_year" class="form-select @error('cohort_year') is-invalid @enderror" required>
                                    <option value="">-- Select Year --</option>
                                    @for ($year = 2025; $year <= 2035; $year++)
                                        <option value="{{ $year }}" {{ old('cohort_year', $beneficiary->cohort_year ?? '') == $year ? 'selected' : '' }}>{{ $year }}</option>
                                    @endfor
                                </select>
                                @error('cohort_year') <div class="invalid-feedback">{{ $message }}</div> @enderror
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Training Centre</label>
                                <select name="training_centre" class="form-select">
                                    <option value="Acacia" {{ old('training_centre', $beneficiary->training_centre ?? '') === 'Acacia' ? 'selected' : '' }}>Acacia</option>
                                    <option value="Women Centre" {{ old('training_centre', $beneficiary->training_centre ?? '') === 'Women Centre' ? 'selected' : '' }}>Women Centre</option>
                                    <option value="Orange Corner" {{ old('training_centre', $beneficiary->training_centre ?? '') === 'Orange Corner' ? 'selected' : '' }}>Orange Corner</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Mobile Number</label>
                                <input type="text" name="mobile_no" class="form-control"
                                       value="{{ old('mobile_no', $beneficiary->mobile_no ?? '') }}">
                            </div>
                        </div>

                        <!-- LOCATION & DEMOGRAPHICS -->
                        <h5 class="mt-5 text-primary">Location & Demographics</h5>
                        <hr>

                        <div class="row g-3">
                            <div class="col-md-4">
                                <label class="form-label">County</label>
                                <input type="text" name="county" class="form-control" value="{{ old('county', $beneficiary->county ?? '') }}">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Payam</label>
                                <input type="text" name="payam" class="form-control" value="{{ old('payam', $beneficiary->payam ?? '') }}">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Boma</label>
                                <input type="text" name="boma" class="form-control" value="{{ old('boma', $beneficiary->boma ?? '') }}">
                            </div>
                        </div>

                        <div class="row g-3 mt-3">
                            <div class="col-md-3">
                                <label class="form-label">Age</label>
                                <input type="number" name="age" class="form-control" min="14" max="100"
                                       value="{{ old('age', $beneficiary->age ?? '') }}">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Gender</label>
                                <select name="gender" class="form-select">
                                    <option value="Female" {{ old('gender', $beneficiary->gender ?? '') === 'Female' ? 'selected' : '' }}>Female</option>
                                    <option value="Male" {{ old('gender', $beneficiary->gender ?? '') === 'Male' ? 'selected' : '' }}>Male</option>
                                    <option value="Adol.Girl" {{ old('gender', $beneficiary->gender ?? '') === 'Adol.Girl' ? 'selected' : '' }}>Adolescent Girl</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Residential Status</label>
                                <select name="residential_status" class="form-select">
                                    <option value="Host" {{ old('residential_status', $beneficiary->residential_status ?? '') === 'Host' ? 'selected' : '' }}>Host</option>
                                    <option value="Returnee" {{ old('residential_status', $beneficiary->residential_status ?? '') === 'Returnee' ? 'selected' : '' }}>Returnee</option>
                                    <option value="IDP" {{ old('residential_status', $beneficiary->residential_status ?? '') === 'IDP' ? 'selected' : '' }}>IDP</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Physical Verification Completed</label>
                                <select name="physical_verification" class="form-select">
                                    <option value="Yes" {{ old('physical_verification', $beneficiary->physical_verification ?? '') === 'Yes' ? 'selected' : '' }}>Yes</option>
                                    <option value="No" {{ old('physical_verification', $beneficiary->physical_verification ?? '') === 'No' ? 'selected' : '' }} selected>No</option>
                                </select>
                            </div>
                        </div>

                        <!-- NEW CAPACITY BUILDING SECTION - REPLACE WITH THIS -->
                        <h5 class="mt-5 text-primary">Capacity Building & Progression</h5>
                        <hr class="border-primary">

                        <!-- 1. Bootcamp Training (5 Modules) -->
                        <div class="card mb-4 border-primary">
                            <div class="card-header bg-primary text-white">
                                <h6 class="mb-0">Bootcamp Training (5 Modules)</h6>
                            </div>
                            <div class="card-body">
                                <div class="row g-3">
                                    @for ($i = 1; $i <= 5; $i++)
                                        <div class="col-md-6">
                                            <label class="form-label">Module {{ $i }}</label>
                                            <select name="bootcamp_module_{{ $i }}" class="form-select @error("bootcamp_module_{$i}") is-invalid @enderror" required>
                                                <option value="Not Completed" {{ old("bootcamp_module_{$i}", $beneficiary->{"bootcamp_module_{$i}"} ?? 'Not Completed') === 'Not Completed' ? 'selected' : '' }}>
                                                    Not Completed
                                                </option>
                                                <option value="Completed" {{ old("bootcamp_module_{$i}", $beneficiary->{"bootcamp_module_{$i}"} ?? '') === 'Completed' ? 'selected' : '' }}>
                                                    Completed
                                                </option>
                                            </select>
                                            @error("bootcamp_module_{$i}") <div class="invalid-feedback">{{ $message }}</div> @enderror
                                        </div>
                                    @endfor
                                </div>
                            </div>
                        </div>

                        <!-- 2. Pitch Competition -->
                        <div class="card mb-4 border-success">
                            <div class="card-header bg-success text-white">
                                <h6 class="mb-0">Pitch Competition</h6>
                            </div>
                            <div class="card-body">
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <label class="form-label">Pitch Presentation <span class="text-danger">*</span></label>
                                        <select name="pitch_presentation" class="form-select @error('pitch_presentation') is-invalid @enderror" id="pitchPresentation" required>
                                            <option value="Not Completed" {{ old('pitch_presentation', $beneficiary->pitch_presentation ?? 'Not Completed') === 'Not Completed' ? 'selected' : '' }}>
                                                Not Completed
                                            </option>
                                            <option value="Completed" {{ old('pitch_presentation', $beneficiary->pitch_presentation ?? '') === 'Completed' ? 'selected' : '' }}>
                                                Completed
                                            </option>
                                        </select>
                                        @error('pitch_presentation') <div class="invalid-feedback">{{ $message }}</div> @enderror
                                    </div>

                                    <div class="col-md-6">
                                        <label class="form-label">Outcome of Pitch</label>
                                        <select name="pitch_outcome" class="form-select @error('pitch_outcome') is-invalid @enderror" id="pitchOutcome">
                                            <option value="">-- Select if applicable --</option>
                                            <option value="Passed" {{ old('pitch_outcome', $beneficiary->pitch_outcome ?? '') === 'Passed' ? 'selected' : '' }}>Passed</option>
                                            <option value="Failed" {{ old('pitch_outcome', $beneficiary->pitch_outcome ?? '') === 'Failed' ? 'selected' : '' }}>Failed</option>
                                        </select>
                                        @error('pitch_outcome') <div class="invalid-feedback">{{ $message }}</div> @enderror
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 3. Accelerator Training (10 Modules) -->
                        <div class="card mb-4 border-info" id="acceleratorBlock" style="opacity: 0.5; pointer-events: none;">
                            <div class="card-header bg-info text-white">
                                <h6 class="mb-0">Accelerator Training (10 Modules – Leave blank if not participated)</h6>
                            </div>
                            <div class="card-body">
                                <div class="row g-3">
                                    @for ($i = 1; $i <= 10; $i++)
                                        <div class="col-md-6">
                                            <label class="form-label">Module {{ $i }}</label>
                                            <select name="accelerator_module_{{ $i }}" class="form-select accelerator-module @error("accelerator_module_{$i}") is-invalid @enderror" disabled>
                                                <option value="">Not Participated / Not Assessed</option>
                                                <option value="Passed" {{ old("accelerator_module_{$i}", $beneficiary->{"accelerator_module_{$i}"} ?? '') === 'Passed' ? 'selected' : '' }}>
                                                    Passed
                                                </option>
                                                <option value="Failed" {{ old("accelerator_module_{$i}", $beneficiary->{"accelerator_module_{$i}"} ?? '') === 'Failed' ? 'selected' : '' }}>
                                                    Failed
                                                </option>
                                            </select>
                                            @error("accelerator_module_{$i}") <div class="invalid-feedback">{{ $message }}</div> @enderror
                                        </div>
                                    @endfor
                                </div>
                            </div>
                        </div>

                        <!-- WEOF CONNECT & CERTIFICATE -->
                        <div class="row g-3 mt-4">
                            <div class="col-md-6">
                                <label class="form-label">WEOF Connect Participation (# of times)</label>
                                <input type="number" name="woef_connect_participation" min="0" class="form-control"
                                       value="{{ old('woef_connect_participation', $beneficiary->woef_connect_participation ?? 0) }}">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Received Certificate?</label>
                                <select name="received_certificate" class="form-select">
                                    <option value="Received" {{ old('received_certificate', $beneficiary->received_certificate ?? '') === 'Received' ? 'selected' : '' }}>Received</option>
                                    <option value="Not received" {{ old('received_certificate', $beneficiary->received_certificate ?? '') !== 'Received' ? 'selected' : '' }}>Not received</option>
                                </select>
                            </div>
                        </div>

                        <!-- GRANT SUB-FORM -->
                        <h5 class="mt-5 text-success">Grant & Disbursement Details</h5>
                        <hr class="border-success">

                        @if(isset($beneficiary) && $beneficiary->grant)
                            @php $g = $beneficiary->grant; @endphp
                        @else
                            @php $g = null; @endphp
                        @endif

                        <div class="row g-3">
                            <div class="col-md-6">
                                <label>Bank Name</label>
                                <input type="text" name="grant[bank_name]" class="form-control"
                                       value="{{ old('grant.bank_name', $g->bank_name ?? '') }}">
                            </div>
                            <div class="col-md-6">
                                <label>Total Approved (USD)</label>
                                <input type="number" step="0.01" name="grant[total_approved]" class="form-control"
                                       value="{{ old('grant.total_approved', $g->total_approved ?? '') }}">
                            </div>
                        </div>

                        <div class="row g-3 mt-3">
                            <div class="col-md-6">
                                <label>1st Tranche Amount</label>
                                <input type="number" step="0.01" name="grant[first_tranche_amount]" class="form-control"
                                       value="{{ old('grant.first_tranche_amount', $g->first_tranche_amount ?? '') }}">
                            </div>
                            <div class="col-md-6">
                                <label>1st Tranche Date</label>
                                <input type="date" name="grant[first_tranche_date]" class="form-control"
                                       value="{{ old('grant.first_tranche_date', $g?->first_tranche_date?->format('Y-m-d') ?? '') }}">
                            </div>                        
                            <div class="col-md-6">
                                <label>Status of Tranche 1</label>
                                <select name="grant[tranche1_utilized_for_plan]" id="tranche1Status" class="form-select">
                                    @foreach(['Fully Utilized','Partially Utilized','Not Yet', 'Misused'] as $opt)
                                        <option value="{{ $opt }}" {{ old('grant.tranche1_utilized_for_plan', $g->tranche1_utilized_for_plan ?? 'Not Yet') === $opt ? 'selected' : '' }}>
                                            {{ $opt }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label>Remarks</label>
                                <textarea name="grant[tranche1_remarks]" class="form-control" rows="2">{{ old('grant.tranche1_remarks', $g->tranche1_remarks ?? '') }}</textarea>
                            </div>                            
                        </div>

                        <div class="row g-3 mt-3" id="tranche2Block" style="opacity: 0.5; pointer-events: none;">
                            <div class="col-md-6">
                                <label>2nd Tranche Amount</label>
                                <input type="number" step="0.01" name="grant[second_tranche_amount]" class="form-control" disabled
                                       value="{{ old('grant.second_tranche_amount', $g->second_tranche_amount ?? '0') }}">
                            </div>
                            <div class="col-md-6">
                                <label>2nd Tranche Date</label>
                                <input type="date" name="grant[second_tranche_date]" class="form-control" disabled
                                       value="{{ old('grant.second_tranche_date', $g?->second_tranche_date?->format('Y-m-d') ?? '') }}">
                            </div>
                        </div>

                        <div class="row g-3 mt-3" id="tranche2StatusBlock" style="opacity: 0.5; pointer-events: none;">
                            <div class="col-md-6">
                                <label>Status of Tranche 2</label>
                                <select name="grant[tranche2_utilized_for_plan]" id="tranche2Status" class="form-select" disabled>
                                    @foreach(['Fully Utilized','Partially Utilized','Not Yet', 'Misused'] as $opt)
                                        <option value="{{ $opt }}" {{ old('grant.tranche2_utilized_for_plan', $g->tranche2_utilized_for_plan ?? 'Not Yet') === $opt ? 'selected' : '' }}>
                                            {{ $opt }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label>Remarks</label>
                                <textarea name="grant[tranche2_remarks]" id="tranche2Remarks" class="form-control" rows="2" disabled>{{ old('grant.tranche2_remarks', $g->tranche2_remarks ?? '') }}</textarea>
                            </div>
                        </div>

                        <!-- SUBMIT -->
                        <div class="mt-5 text-end">
                            <a href="{{ route('component2.seedlab.index') }}" class="btn btn-secondary me-3">Cancel</a>
                            <button type="submit" class="btn btn-success btn-lg">
                                <i class="fas fa-save"></i>
                                {{ isset($beneficiary) ? 'Update Beneficiary' : 'Save Beneficiary' }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const presentationSelect = document.getElementById('pitchPresentation');
        const outcomeSelect = document.getElementById('pitchOutcome');
        const tranche1Status = document.getElementById('tranche1Status');
        const acceleratorBlock = document.getElementById('acceleratorBlock');
        const acceleratorModules = document.querySelectorAll('.accelerator-module');
        const tranche2Block = document.getElementById('tranche2Block');
        const tranche2StatusBlock = document.getElementById('tranche2StatusBlock');
        const tranche2Inputs = document.querySelectorAll('#tranche2Block input, #tranche2StatusBlock input, #tranche2StatusBlock select, #tranche2StatusBlock textarea');

        // Handle Pitch Presentation conditional logic
        function toggleOutcome() {
            if (presentationSelect.value === 'Completed') {
                outcomeSelect.disabled = false;
                outcomeSelect.required = true; // optional: enforce if presentation completed
            } else {
                outcomeSelect.disabled = true;
                outcomeSelect.value = ''; // clear when disabled
                outcomeSelect.required = false;
            }
        }

        // Handle Accelerator Training conditional logic
        function toggleAccelerator() {
            if (outcomeSelect.value === 'Passed') {
                // Enable Accelerator Training
                acceleratorBlock.style.opacity = '1';
                acceleratorBlock.style.pointerEvents = 'auto';
                acceleratorModules.forEach(module => module.disabled = false);
            } else {
                // Disable Accelerator Training
                acceleratorBlock.style.opacity = '0.5';
                acceleratorBlock.style.pointerEvents = 'none';
                acceleratorModules.forEach(module => {
                    module.disabled = true;
                    module.value = ''; // clear selection
                });
            }
        }

        // Handle Tranche 2 conditional logic
        function toggleTranche2() {
            if (tranche1Status.value === 'Fully Utilized') {
                // Enable Tranche 2
                tranche2Block.style.opacity = '1';
                tranche2Block.style.pointerEvents = 'auto';
                tranche2StatusBlock.style.opacity = '1';
                tranche2StatusBlock.style.pointerEvents = 'auto';
                tranche2Inputs.forEach(input => input.disabled = false);
            } else {
                // Disable Tranche 2
                tranche2Block.style.opacity = '0.5';
                tranche2Block.style.pointerEvents = 'none';
                tranche2StatusBlock.style.opacity = '0.5';
                tranche2StatusBlock.style.pointerEvents = 'none';
                tranche2Inputs.forEach(input => input.disabled = true);
            }
        }

        presentationSelect.addEventListener('change', toggleOutcome);
        outcomeSelect.addEventListener('change', toggleAccelerator);
        tranche1Status.addEventListener('change', toggleTranche2);
        
        toggleOutcome(); // run on load
        toggleAccelerator(); // run on load
        toggleTranche2(); // run on load
    });
</script>
@endsection