<!-- Main Content -->
<?php $is_view_only = isset($is_view_only) && $is_view_only; ?>
<div class="content">
    <div class="card position-relative shadow-sm rounded-4">
        <div class="fab-top-group" style="display: flex; gap: 8px; position: absolute; top: 8px; right: 25px; z-index: 10;">
            <a href="<?= base_url('type/allType/' . $company->id) ?>" class="btn btn-outline-secondary btn-sm" title="Back to List" style="border-radius: 50%; width: 36px; height: 36px; padding: 0; display: flex; align-items: center; justify-content: center;">
                <i class="fa fa-arrow-left"></i>
            </a>
        </div>
        
        <div class="card-body">
            <?php if ($is_view_only): ?>
            <div class="alert alert-info alert-dismissible fade show mb-3" role="alert">
                <i class="fas fa-eye"></i> <strong>View Only Mode:</strong> This document head has <?= $has_uploads ?> uploaded document(s) and cannot be edited.
            </div>
            <?php endif; ?>
            
            <form action="<?= base_url('companydocheads/save') ?>" method="post">
                <input type="hidden" name="company_id" value="<?= $company->id ?>">
                <input type="hidden" name="type_id" value="<?= $doc_head->id ?>">
                
                <!-- Basic Info -->
                <div class="row mb-4">
                    <div class="col-md-6">
                        <div class="card bg-light">
                            <div class="card-body">
                                <h6 class="card-title text-primary"><i class="fas fa-file-alt"></i> Document Head Information</h6>
                                <table class="table table-sm table-borderless mb-0">
                                    <tr>
                                        <td width="40%"><strong>Authority:</strong></td>
                                        <td><?= htmlspecialchars($doc_head->authority_name) ?></td>
                                    </tr>
                                    <tr>
                                        <td><strong>Document Head:</strong></td>
                                        <td><?= htmlspecialchars($doc_head->type_name) ?></td>
                                    </tr>
                                    <tr>
                                        <td><strong>Alias:</strong></td>
                                        <td><?= htmlspecialchars($doc_head->alias_name) ?: '-' ?></td>
                                    </tr>
                                    <tr>
                                        <td><strong>Frequency:</strong></td>
                                        <td><?= ucfirst($doc_head->frequency) ?></td>
                                    </tr>
                                    <!--<tr>
                                        <td><strong>Master Start Date:</strong></td>
                                        <td><?= $doc_head->document_start_date ? date('d-M-Y', strtotime($doc_head->document_start_date)) : '-' ?></td>
                                    </tr>-->
                                </table>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card bg-light">
                            <div class="card-body">
                                <h6 class="card-title text-primary"><i class="fas fa-building"></i> Company Information</h6>
                                <table class="table table-sm table-borderless mb-0">
                                    <tr>
                                        <td width="40%"><strong>Company:</strong></td>
                                        <td><?= htmlspecialchars($company->company_name) ?></td>
                                    </tr>
                                    <tr>
                                        <td><strong>Company Start Date:</strong></td>
                                        <td><strong class="text-primary"><?= date('d-M-Y', strtotime($company->co_start_date)) ?></strong></td>
                                    </tr>
                                    <tr>
                                        <td><strong>Current Status:</strong></td>
                                        <td>
                                            <?php if ($company_settings && $company_settings->is_enabled): ?>
                                                <span class="badge bg-success">🟢 Active</span>
                                            <?php elseif ($company_settings && $company_settings->is_reviewed): ?>
                                                <span class="badge bg-warning text-dark">🟡 Reviewed</span>
                                            <?php elseif ($company_settings): ?>
                                                <span class="badge bg-danger">🔴 Pending Review</span>
                                            <?php else: ?>
                                                <span class="badge bg-secondary">⚪ Not Configured</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php //if ($company_settings && $company_settings->enabled_at): ?>
                                    <tr>
                                        <td><strong>Financial Year:</strong></td>
                                        <td><?= $company->fiscal_year ?></td>
                                    </tr>
                                    <?php //endif; ?>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Custom Settings -->
                <div class="row mb-4">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header bg-primary text-white py-2">
                                <h6 class="mb-0"><i class="fas fa-cog"></i> Custom Settings</h6>
                            </div>
                            <div class="card-body py-2">
                                <?php 
                                // Get due day - company settings first (if not empty), then master template
                                $due_day_value = '';
                                if ($company_settings && !empty($company_settings->custom_frequency_start_date)) {
                                    $due_day_value = $company_settings->custom_frequency_start_date;
                                } elseif (!empty($doc_head->frequency_start_date)) {
                                    $due_day_value = $doc_head->frequency_start_date;
                                }
                                // Determine due in same/next value
                                $due_in_same_next = '';
                                if ($company_settings && !empty($company_settings->custom_due_in_same_next_month)) {
                                    $due_in_same_next = $company_settings->custom_due_in_same_next_month;
                                } elseif (isset($doc_head->due_in_same_next_month) && $doc_head->due_in_same_next_month !== '' && $doc_head->due_in_same_next_month !== null) {
                                    $due_in_same_next = ($doc_head->due_in_same_next_month == '1' || $doc_head->due_in_same_next_month == 'N') ? '1' : '0';
                                }
                                ?>
                                <div class="row mb-2 align-items-center">
                                    <label for="custom_start_date" class="col-sm-5 col-form-label col-form-label-sm">
                                        Start Date <?php if (!$is_view_only): ?><span class="text-danger">*</span><?php endif; ?>
                                    </label>
                                    <div class="col-sm-7">
                                        <input type="date" class="form-control form-control-sm" id="custom_start_date" name="custom_start_date"
                                               value="<?= $company_settings ? $company_settings->custom_start_date : $doc_head->document_start_date ?>"
                                               min="<?= date('Y-m-d', strtotime($company->co_start_date)) ?>" <?= $is_view_only ? 'disabled' : 'required' ?>>
                                    </div>
                                </div>
                                
                                <div class="row mb-2 align-items-center">
                                    <label for="custom_frequency_start_date" class="col-sm-5 col-form-label col-form-label-sm">Due Day</label>
                                    <div class="col-sm-7">
                                        <input type="number" class="form-control form-control-sm" id="custom_frequency_start_date" name="custom_frequency_start_date"
                                               value="<?= $due_day_value ?>" placeholder="e.g., 7" min="1" max="31" <?= $is_view_only ? 'disabled' : 'required' ?>>
                                    </div>
                                </div>
                                
                                <div class="row mb-2 align-items-center">
                                    <label for="custom_due_in_same_next_month" class="col-sm-5 col-form-label col-form-label-sm">Due Month</label>
                                    <div class="col-sm-7">
                                        <select class="form-control form-control-sm" id="custom_due_in_same_next_month" name="custom_due_in_same_next_month" <?= $is_view_only ? 'disabled' : 'required' ?>>
                                            <option value="">-- Select --</option>
                                            <option value="0" <?= ($due_in_same_next === '0') ? 'selected' : '' ?>>Same Month</option>
                                            <option value="1" <?= ($due_in_same_next === '1') ? 'selected' : '' ?>>Next Month</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <!-- Next Due Date -->
                                <div class="row mb-2 align-items-center">
                                    <label class="col-sm-5 col-form-label col-form-label-sm">Next Due Date</label>
                                    <div class="col-sm-7">
                                        <span id="next_due_date_display" class="badge bg-success" style="font-size: 0.9rem; padding: 6px 12px;">-</span>
                                    </div>
                                </div>
                                
                                <small class="text-muted d-block mt-2" style="font-size: 0.7rem;">
                                    <i class="fas fa-info-circle"></i> Start date must be ≥ <?= date('d-M-Y', strtotime($company->co_start_date)) ?>
                                    <?php if (!empty($doc_head->frequency_start_date)): ?>
                                    | Template Due Day: <?= $doc_head->frequency_start_date ?>
                                    <?php endif; ?>
                                </small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <!-- Mandatory Documents -->
                        <div class="card">
                            <div class="card-header bg-info text-white">
                                <h6 class="mb-0"><i class="fas fa-list"></i> Mandatory Documents (<?= count($mandatory_docs) ?>)</h6>
                            </div>
                            <div class="card-body" style="max-height: 280px; overflow-y: auto;">
                                <?php if (!empty($mandatory_docs)): ?>
                                <table class="table table-sm">
                                    <thead>
                                        <tr>
                                            <th>#</th>
                                            <th>Document</th>
                                            <th>Mandatory</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php $i = 1; foreach ($mandatory_docs as $doc): ?>
                                        <tr>
                                            <td><?= $i++ ?></td>
                                            <td><?= htmlspecialchars($doc->document_name) ?></td>
                                            <td>
                                                <?php 
                                                // Check various formats for mandatory flag
                                                $is_mandatory = false;
                                                if (isset($doc->is_mandatory)) {
                                                    $val = $doc->is_mandatory;
                                                    $is_mandatory = ($val === true || $val === 't' || $val === '1' || strtolower($val) === 'yes' || strtolower($val) === 'true');
                                                }
                                                ?>
                                                <?php if ($is_mandatory): ?>
                                                    <span class="badge bg-success">Yes</span>
                                                <?php else: ?>
                                                    <span class="badge bg-secondary">No</span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                                <?php else: ?>
                                <p class="text-muted mb-0">No mandatory documents configured.</p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Reminders -->
                <div class="row mb-4">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header bg-warning">
                                <h6 class="mb-0"><i class="fas fa-bell"></i> Reminders</h6>
                            </div>
                            <div class="card-body">
                                <?php if (!empty($reminders)): ?>
                                <table class="table table-sm">
                                    <thead>
                                        <tr>
                                            <th>Reminder #</th>
                                            <th>Days Before Due</th>
                                            <th>To User</th>
                                            <th>To Admin</th>
                                            <th>To Super Admin</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($reminders as $reminder): ?>
                                        <tr>
                                            <td><?= $reminder->reminder_no ?></td>
                                            <td><?= $reminder->days_before ?> days</td>
                                            <td>
                                                <?php 
                                                $toUser = isset($reminder->reminder_to_user) ? $reminder->reminder_to_user : false;
                                                echo ($toUser === true || $toUser === 't' || $toUser === 'true' || $toUser === '1') ? '<i class="fas fa-check text-success"></i>' : '<i class="fas fa-times text-muted"></i>'; 
                                                ?>
                                            </td>
                                            <td>
                                                <?php 
                                                $toAdmin = isset($reminder->reminder_to_admin) ? $reminder->reminder_to_admin : false;
                                                echo ($toAdmin === true || $toAdmin === 't' || $toAdmin === 'true' || $toAdmin === '1') ? '<i class="fas fa-check text-success"></i>' : '<i class="fas fa-times text-muted"></i>'; 
                                                ?>
                                            </td>
                                            <td>
                                                <?php 
                                                $toSuperAdmin = isset($reminder->reminder_to_super_admin) ? $reminder->reminder_to_super_admin : false;
                                                echo ($toSuperAdmin === true || $toSuperAdmin === 't' || $toSuperAdmin === 'true' || $toSuperAdmin === '1') ? '<i class="fas fa-check text-success"></i>' : '<i class="fas fa-times text-muted"></i>'; 
                                                ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                                <?php else: ?>
                                <p class="text-muted mb-0">
                                    <i class="fas fa-info-circle"></i> No reminders configured for this document head in the master template.
                                    <br><small>Add reminders in Document Head master to show here.</small>
                                </p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Action Buttons -->
                <div class="row">
                    <div class="col-12">
                        <hr>
                        <div class="d-flex justify-content-between">
                            <a href="<?= base_url('type/allType/' . $company->id) ?>" class="btn btn-secondary">
                                <i class="fas fa-arrow-left"></i> <?= $is_view_only ? 'Back' : 'Cancel' ?>
                            </a>
                            <?php if (!$is_view_only): ?>
                            <div>
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save"></i> Save
                                </button>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Get company fiscal year start month (0-indexed)
    const fiscalYear = '<?= $company->fiscal_year ?? "April-March" ?>';
    const fiscalStartMonth = getFiscalStartMonth(fiscalYear);
    const frequency = '<?= strtolower($doc_head->frequency ?? "monthly") ?>';
    
    function getFiscalStartMonth(fy) {
        const map = {
            "January": 0, "February": 1, "March": 2, "April": 3, "May": 4, "June": 5,
            "July": 6, "August": 7, "September": 8, "October": 9, "November": 10, "December": 11
        };
        return map[fy.split("-")[0].trim()] ?? 0;
    }
    
    function calculateNextDueDate() {
        const startDate = $('#custom_start_date').val();
        const dueDay = parseInt($('#custom_frequency_start_date').val(), 10);
        const dueMonth = $('#custom_due_in_same_next_month').val(); // "0" = same, "1" = next
        
        if (!startDate || !dueDay || isNaN(dueDay) || dueMonth === '') {
            $('#next_due_date_display').text('-').removeClass('bg-success bg-warning').addClass('bg-secondary');
            return;
        }
        
        const dueMonthChoice = (dueMonth === '1') ? 'next' : 'same';
        const nextDue = getNextDueDateUniversal({
            fiscalStartMonth0: fiscalStartMonth,
            frequency: frequency,
            dueDay: dueDay,
            documentStartDate: startDate,
            holidaysArr: [],
            dueMonthChoice: dueMonthChoice
        });
        
        if (nextDue) {
            // Format date for display
            const d = new Date(nextDue + 'T00:00:00');
            const options = { day: '2-digit', month: 'short', year: 'numeric' };
            const formatted = d.toLocaleDateString('en-GB', options);
            $('#next_due_date_display').text(formatted).removeClass('bg-secondary bg-warning').addClass('bg-success');
        } else {
            $('#next_due_date_display').text('-').removeClass('bg-success bg-warning').addClass('bg-secondary');
        }
    }
    
    // Next due date calculation (simplified from add_type.php)
    function getNextDueDateUniversal(params) {
        const {
            fiscalStartMonth0 = 0,
            frequency,
            dueDay,
            documentStartDate,
            holidaysArr = [],
            dueMonthChoice = "same"
        } = params;
        
        if (!documentStartDate || !frequency || !dueDay) return "";
        
        const freq = frequency.toString().trim().toLowerCase();
        const start = new Date(documentStartDate + "T00:00:00");
        const startYear = start.getFullYear();
        const startMonth = start.getMonth();
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        
        // ONE-TIME: stay in same month/year as start
        if (freq === "onetime" || freq === "one-time" || freq === "one time") {
            return toISODate(setSafeDate(startYear, startMonth, dueDay));
        }
        
        // Build fiscal month sequence
        const fiscalMonths = [];
        for (let i = 0; i < 12; i++) {
            fiscalMonths.push((fiscalStartMonth0 + i) % 12);
        }
        
        // Map frequency -> period end months based on start date month
        // For yearly: the period is the START MONTH of the document
        // For other frequencies: use fiscal year periods
        let periods = [];
        if (freq === "monthly") {
            periods = fiscalMonths.slice();
        } else if (freq === "quarterly") {
            periods = [fiscalMonths[2], fiscalMonths[5], fiscalMonths[8], fiscalMonths[11]];
        } else if (freq === "half yearly" || freq === "half-yearly" || freq === "half_yearly" || freq === "halfyearly") {
            periods = [fiscalMonths[5], fiscalMonths[11]];
        } else if (freq === "yearly" || freq === "annual") {
            // For yearly, the period is based on the document start month, not fiscal year end
            periods = [startMonth];
        } else {
            periods = fiscalMonths.slice();
        }
        
        const candidates = [];
        
        // Start from document start year, not just today's year
        const searchStartYear = Math.min(startYear, today.getFullYear());
        
        // Check from start year to 2 years in the future
        for (let year = searchStartYear; year <= today.getFullYear() + 2; year++) {
            for (const periodMonth of periods) {
                let dueYear = year;
                let dueMonthIdx = periodMonth;
                
                // Adjust for "next month"
                if (dueMonthChoice === "next") {
                    dueMonthIdx += 1;
                    if (dueMonthIdx > 11) {
                        dueMonthIdx = 0;
                        dueYear++;
                    }
                }
                
                const dueDate = setSafeDate(dueYear, dueMonthIdx, dueDay);
                
                // Check if due date is in the future (or today) and period >= start date
                const periodDate = new Date(year, periodMonth, 1);
                const startDateObj = new Date(start.getFullYear(), start.getMonth(), 1);
                
                // For the first due date, period must be >= start month/year
                // And due date must be >= today
                if (periodDate >= startDateObj && dueDate >= today) {
                    candidates.push(dueDate);
                }
            }
        }
        
        if (candidates.length === 0) return "";
        
        // Sort and return the earliest future due date
        candidates.sort((a, b) => a - b);
        return toISODate(candidates[0]);
    }
    
    function setSafeDate(year, month, day) {
        // Get last day of month to avoid overflow
        const lastDay = new Date(year, month + 1, 0).getDate();
        const safeDay = Math.min(day, lastDay);
        return new Date(year, month, safeDay);
    }
    
    function toISODate(d) {
        const yyyy = d.getFullYear();
        const mm = String(d.getMonth() + 1).padStart(2, '0');
        const dd = String(d.getDate()).padStart(2, '0');
        return `${yyyy}-${mm}-${dd}`;
    }
    
    // Bind change events
    $('#custom_start_date, #custom_frequency_start_date, #custom_due_in_same_next_month').on('change keyup', function() {
        calculateNextDueDate();
    });
    
    // Initial calculation
    calculateNextDueDate();
});
</script>