<!-- Main Content -->
<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('companydocheads/index/' . $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">
            <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 <span class="text-danger">*</span>
                                    </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)) ?>">
                                    </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="text" class="form-control form-control-sm" id="custom_frequency_start_date" name="custom_frequency_start_date"
                                               value="<?= $due_day_value ?>" placeholder="e.g., 7">
                                    </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">
                                            <option value="">-- Select --</option>
                                            <option value="0" <?= ($due_in_same_next == 'S' || $due_in_same_next == '0') ? 'selected' : '' ?>>Same Month</option>
                                            <option value="1" <?= ($due_in_same_next == 'N' || $due_in_same_next == '1') ? 'selected' : '' ?>>Next Month</option>
                                        </select>
                                    </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('companydocheads/index/' . $company->id) ?>" class="btn btn-secondary">
                                <i class="fas fa-arrow-left"></i> Cancel
                            </a>
                            <div>
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save"></i> Save & Mark Reviewed
                                </button>
                                
                                <?php if (!$company_settings || !$company_settings->is_enabled): ?>
                                    <?php if (can('company_doc_heads.activate')): ?>
                                    <button type="button" class="btn btn-success ms-2" onclick="activateFromEdit()">
                                        <i class="fas fa-check"></i> Save & Activate
                                    </button>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function activateFromEdit() {
    var startDate = document.getElementById('custom_start_date').value;
    
    if (!startDate) {
        alert('Please enter a document start date before activating.');
        return;
    }
    
    var companyStartDate = '<?= date('Y-m-d', strtotime($company->co_start_date)) ?>';
    if (startDate < companyStartDate) {
        alert('Document start date cannot be earlier than company start date (<?= date('d-M-Y', strtotime($company->co_start_date)) ?>)');
        return;
    }
    
    if (!confirm('Are you sure you want to activate this document head? This will enable it for uploads and reports.')) {
        return;
    }
    
    $.ajax({
        url: '<?= base_url('companydocheads/activate') ?>',
        type: 'POST',
        data: {
            company_id: <?= $company->id ?>,
            type_id: <?= $doc_head->id ?>,
            custom_start_date: startDate
        },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                alert(response.message);
                window.location.href = '<?= base_url('companydocheads/index/' . $company->id) ?>';
            } else {
                alert('Error: ' + response.message);
            }
        },
        error: function() {
            alert('An error occurred. Please try again.');
        }
    });
}

// Validate start date on change
document.getElementById('custom_start_date').addEventListener('change', function() {
    var companyStartDate = '<?= date('Y-m-d', strtotime($company->co_start_date)) ?>';
    if (this.value < companyStartDate) {
        alert('Document start date cannot be earlier than company start date (<?= date('d-M-Y', strtotime($company->co_start_date)) ?>)');
        this.value = companyStartDate;
    }
});
</script>
