

<?php $__env->startSection('content'); ?>
<div class="container-fluid px-4 py-6">
    <div class="max-w-4xl mx-auto">
        <!-- Header -->
        <div class="d-flex align-items-center mb-4">
            <a href="<?php echo e(route('deployments.index')); ?>" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to Deployments
            </a>
        </div>

        <!-- Form Card -->
        <div class="card shadow-sm">
            <div class="card-header bg-white py-3">
                <h4 class="mb-0">Create New Deployment</h4>
            </div>
            <div class="card-body p-4">
                <?php if($errors->any()): ?>
                    <div class="alert alert-danger">
                        <ul class="mb-0">
                            <?php $__currentLoopData = $errors->all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $error): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <li><?php echo e($error); ?></li>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </ul>
                    </div>
                <?php endif; ?>

                <form action="<?php echo e(route('deployments.store')); ?>" method="POST" enctype="multipart/form-data">
                    <?php echo csrf_field(); ?>

                    <!-- Select NDRT Officer -->
                    <div class="mb-4">
                        <label for="ndrt_officer_id" class="form-label fw-semibold">Select NDRT Officer <span class="text-danger">*</span></label>
                        <select class="form-select" id="ndrt_officer_id" name="ndrt_officer_id" required>
                            <option value="">-- Select Officer --</option>
                            <?php $__empty_1 = true; $__currentLoopData = $officers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $officer): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                <option value="<?php echo e($officer->id); ?>" 
                                        data-deployment-months="<?php echo e(json_encode($officer->deployment_months ?? [])); ?>"
                                        <?php echo e(old('ndrt_officer_id') == $officer->id ? 'selected' : ''); ?>>
                                    <?php echo e($officer->name ?? ($officer->first_name . ' ' . $officer->surname)); ?>

                                </option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                                <option value="">No officers available</option>
                            <?php endif; ?>
                        </select>
                        <div id="officer_availability_info" class="mt-2"></div>
                    </div>

                    <!-- Deployment Period -->
                    <div class="row mb-4">
                        <div class="col-md-4">
                            <label for="start_date" class="form-label fw-semibold">Start Date <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo e(old('start_date')); ?>" required>
                            <small id="start_date_warning" class="text-danger d-none"></small>
                        </div>
                        <div class="col-md-4">
                            <label for="end_date" class="form-label fw-semibold">End Date <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo e(old('end_date')); ?>" required>
                            <small id="end_date_warning" class="text-danger d-none"></small>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-semibold">Duration</label>
                            <div class="form-control bg-light" id="duration-display">0 days</div>
                        </div>
                    </div>

                    <!-- Mentor -->
                    <div class="row mb-4">
                        <div class="col-md-4">
                            <label class="form-label fw-semibold d-block">Deployed with Mentor? <span class="text-danger">*</span></label>
                            <div class="d-flex gap-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="has_mentor" id="has_mentor_yes" value="1" <?php echo e(old('has_mentor') == '1' ? 'checked' : ''); ?>>
                                    <label class="form-check-label" for="has_mentor_yes">Yes</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="has_mentor" id="has_mentor_no" value="0" <?php echo e(old('has_mentor','0') == '0' ? 'checked' : ''); ?>>
                                    <label class="form-check-label" for="has_mentor_no">No</label>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-8" id="mentor_name_wrapper" style="display: none;">
                            <label for="mentor_name" class="form-label fw-semibold">Mentor Name</label>
                            <input type="text" class="form-control" id="mentor_name" name="mentor_name" value="<?php echo e(old('mentor_name')); ?>" placeholder="Enter mentor's name">
                        </div>
                    </div>

                    <!-- Extension -->
                    <div class="row mb-4">
                        <div class="col-md-4">
                            <label class="form-label fw-semibold d-block">Mission Extended?</label>
                            <div class="d-flex gap-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="is_extended" id="is_extended_yes" value="1" <?php echo e(old('is_extended') == '1' ? 'checked' : ''); ?>>
                                    <label class="form-check-label" for="is_extended_yes">Yes</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="is_extended" id="is_extended_no" value="0" <?php echo e(old('is_extended','0') == '0' ? 'checked' : ''); ?>>
                                    <label class="form-check-label" for="is_extended_no">No</label>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4" id="new_completion_date_wrapper" style="display: none;">
                            <label for="new_completion_date" class="form-label fw-semibold">New Completion Date</label>
                            <input type="date" class="form-control" id="new_completion_date" name="new_completion_date" value="<?php echo e(old('new_completion_date')); ?>">
                        </div>
                        <div class="col-md-4" id="extension_reason_wrapper" style="display: none;">
                            <label for="extension_reason" class="form-label fw-semibold">Reason for Extension</label>
                            <input type="text" class="form-control" id="extension_reason" name="extension_reason" value="<?php echo e(old('extension_reason')); ?>" placeholder="Provide reason">
                        </div>
                    </div>

                    <!-- Status and Mission end date -->
                    <div class="row mb-4">
                        <?php if(Auth::user()->isAdmin() || Auth::user()->isOperationsManager()): ?>
                        <div class="col-md-4">
                            <label for="status" class="form-label fw-semibold">Status <span class="text-danger">*</span></label>
                            <select id="status" name="status" class="form-select" required>
                                <option value="pending" <?php echo e(old('status','pending') === 'pending' ? 'selected' : ''); ?>>Pending</option>
                                <option value="active" <?php echo e(old('status','active') === 'active' ? 'selected' : ''); ?>>Active</option>
                                <option value="completed" <?php echo e(old('status') === 'completed' ? 'selected' : ''); ?>>Completed</option>
                            </select>
                        </div>
                        <?php else: ?>
                        <div class="col-md-4">
                            <label for="status" class="form-label fw-semibold">Status <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="status" name="status" value="pending" placeholder="Pending" readonly>
                        </div>
                        <?php endif; ?>
                        <div class="col-md-4" id="mission_end_date_wrapper" style="display: none;">
                            <label for="mission_end_date" class="form-label fw-semibold">Actual Completion Date</label>
                            <input type="date" class="form-control" id="mission_end_date" name="mission_end_date" value="<?php echo e(old('mission_end_date')); ?>">
                        </div>
                    </div>

                    <!-- Mission Location -->
                    <div class="mb-4">
                        <label for="mission_location" class="form-label fw-semibold">Mission Location <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="mission_location" name="mission_location" value="<?php echo e(old('mission_location')); ?>" required placeholder="Enter mission location">
                    </div>

                    <!-- Mission Description -->
                    <div class="mb-4">
                        <label for="mission_description" class="form-label fw-semibold">Brief Description of the Mission <span class="text-danger">*</span></label>
                        <textarea class="form-control" id="mission_description" name="mission_description" rows="4" required placeholder="Describe the mission objectives and scope..."><?php echo e(old('mission_description')); ?></textarea>
                    </div>

                    <!-- Reporting To -->
                    <div class="mb-4">
                        <label for="reporting_to" class="form-label fw-semibold">Reporting To</label>
                        <input type="text" class="form-control" id="reporting_to" name="reporting_to" value="<?php echo e(old('reporting_to')); ?>" placeholder="Name or role being reported to">
                    </div>

                    <!-- Equipment Log -->
                    <div class="mb-4">
                        <label class="form-label fw-semibold d-block">Equipment Log</label>
                        <p class="text-muted small mb-2">List items issued (e.g., Laptop, Office Phone, Others)</p>
                        <div id="equipment_list">
                            <?php
                                $equipment = old('equipment_log', []);
                                if (empty($equipment)) { $equipment = ['']; }
                            ?>
                            <?php $__currentLoopData = $equipment; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $idx => $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <div class="d-flex gap-2 mb-2 equipment-item">
                                    <input type="text" class="form-control" name="equipment_log[]" value="<?php echo e($item); ?>" placeholder="Equipment item">
                                    <button type="button" class="btn btn-outline-danger remove-equipment" aria-label="Remove"><i class="bi bi-dash"></i></button>
                                </div>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </div>
                        <button type="button" class="btn btn-outline-primary btn-sm" id="add_equipment">
                            <i class="bi bi-plus-lg"></i> Add Equipment
                        </button>
                    </div>

                    <!-- Upload Report (optional) -->
                    <div class="mb-4">
                        <label for="report_path" class="form-label fw-semibold">Upload Deployment Report (optional)</label>
                        <input type="file" class="form-control" id="report_path" name="report_file" accept=".pdf,.doc,.docx">
                        <small class="text-muted">PDF or DOC up to 10MB</small>
                    </div>

                    <!-- Submit Buttons -->
                    <div class="d-flex gap-2 pt-3">
                        <button type="submit" class="btn btn-success px-4" id="submit_btn">
                            <i class="fas fa-save"></i> Save Deployment
                        </button>
                        <a href="<?php echo e(route('deployments.index')); ?>" class="btn btn-outline-secondary px-4">Cancel</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php $__env->startPush('scripts'); ?>
<script>
    let officerAvailableMonths = [];
    const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 
                       'July', 'August', 'September', 'October', 'November', 'December'];

    function calculateDuration() {
        const startDate = document.getElementById('start_date').value;
        const endDate = document.getElementById('end_date').value;
        if (startDate && endDate) {
            const start = new Date(startDate);
            const end = new Date(endDate);
            const diffTime = Math.abs(end - start);
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1;
            document.getElementById('duration-display').textContent = diffDays + ' day' + (diffDays !== 1 ? 's' : '');
        }
    }

    function toggleMentor() {
        const hasMentor = document.querySelector('input[name="has_mentor"]:checked')?.value === '1';
        document.getElementById('mentor_name_wrapper').style.display = hasMentor ? '' : 'none';
    }

    function toggleExtension() {
        const isExtended = document.querySelector('input[name="is_extended"]:checked')?.value === '1';
        document.getElementById('new_completion_date_wrapper').style.display = isExtended ? '' : 'none';
        document.getElementById('extension_reason_wrapper').style.display = isExtended ? '' : 'none';
    }

    function toggleMissionEndByStatus() {
        const status = document.getElementById('status').value;
        document.getElementById('mission_end_date_wrapper').style.display = status === 'completed' ? '' : 'none';
    }

    function updateOfficerAvailability() {
        const select = document.getElementById('ndrt_officer_id');
        const selectedOption = select.options[select.selectedIndex];
        const infoDiv = document.getElementById('officer_availability_info');
        
        if (selectedOption && selectedOption.value) {
            const months = JSON.parse(selectedOption.dataset.deploymentMonths || '[]');
            officerAvailableMonths = months;
            
            if (months.length > 0) {
                infoDiv.innerHTML = `<div class="alert alert-info py-2 px-3 mb-0">
                    <i class="fas fa-info-circle"></i> <strong>Available months:</strong> ${months.join(', ')}
                </div>`;
            } else {
                infoDiv.innerHTML = `<div class="alert alert-warning py-2 px-3 mb-0">
                    <i class="fas fa-exclamation-triangle"></i> This officer has no available deployment months set.
                </div>`;
            }
            
            validateDeploymentDates();
        } else {
            infoDiv.innerHTML = '';
            officerAvailableMonths = [];
        }
    }

    function validateDeploymentDates() {
        const startDate = document.getElementById('start_date').value;
        const endDate = document.getElementById('end_date').value;
        const startWarning = document.getElementById('start_date_warning');
        const endWarning = document.getElementById('end_date_warning');
        const submitBtn = document.getElementById('submit_btn');
        
        startWarning.classList.add('d-none');
        endWarning.classList.add('d-none');
        
        if (!startDate || !endDate || officerAvailableMonths.length === 0) {
            submitBtn.disabled = officerAvailableMonths.length === 0;
            return;
        }
        
        const start = new Date(startDate);
        const end = new Date(endDate);
        
        // Get all months in the deployment period
        let current = new Date(start);
        let deploymentMonths = [];
        let hasInvalidMonth = false;
        
        while (current <= end) {
            const monthName = monthNames[current.getMonth()];
            if (!deploymentMonths.includes(monthName)) {
                deploymentMonths.push(monthName);
            }
            
            if (!officerAvailableMonths.includes(monthName)) {
                hasInvalidMonth = true;
            }
            
            current.setMonth(current.getMonth() + 1);
        }
        
        if (hasInvalidMonth) {
            const unavailableMonths = deploymentMonths.filter(m => !officerAvailableMonths.includes(m));
            const warningMsg = `Officer not available in: ${unavailableMonths.join(', ')}`;
            
            startWarning.textContent = warningMsg;
            startWarning.classList.remove('d-none');
            submitBtn.disabled = true;
        } else {
            submitBtn.disabled = false;
        }
    }

    // Event listeners
    document.getElementById('ndrt_officer_id').addEventListener('change', updateOfficerAvailability);
    document.getElementById('start_date').addEventListener('change', function() {
        calculateDuration();
        validateDeploymentDates();
    });
    document.getElementById('end_date').addEventListener('change', function() {
        calculateDuration();
        validateDeploymentDates();
    });
    document.querySelectorAll('input[name="has_mentor"]').forEach(r => r.addEventListener('change', toggleMentor));
    document.querySelectorAll('input[name="is_extended"]').forEach(r => r.addEventListener('change', toggleExtension));
    document.getElementById('status').addEventListener('change', toggleMissionEndByStatus);

    // Equipment add/remove
    document.getElementById('add_equipment').addEventListener('click', function () {
        const container = document.getElementById('equipment_list');
        const row = document.createElement('div');
        row.className = 'd-flex gap-2 mb-2 equipment-item';
        row.innerHTML = `
            <input type="text" class="form-control" name="equipment_log[]" placeholder="Equipment item">
            <button type="button" class="btn btn-outline-danger remove-equipment" aria-label="Remove"><i class="bi bi-dash"></i></button>
        `;
        container.appendChild(row);
    });

    document.getElementById('equipment_list').addEventListener('click', function (e) {
        if (e.target.closest('.remove-equipment')) {
            const item = e.target.closest('.equipment-item');
            if (item && document.querySelectorAll('#equipment_list .equipment-item').length > 1) {
                item.remove();
            }
        }
    });

    // Initialize
    calculateDuration();
    toggleMentor();
    toggleExtension();
    toggleMissionEndByStatus();
    updateOfficerAvailability();
</script>
<?php $__env->stopPush(); ?>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/vmisssredcross/nrdt.vmis-ssredcross.org/resources/views/deployments/create.blade.php ENDPATH**/ ?>