<?php
require_once __DIR__ . '/../../../bootstrap/auth.php';
requireLogin();

// Check admin permission
require_once __DIR__ . '/../../../app/Models/UserType.php';
$userTypeModel = new UserType();
if (!$userTypeModel->hasPermission($_SESSION['user_type_id'], 'languages_view')) {
    http_response_code(403);
    die('Access denied');
}

require_once __DIR__ . '/../../../app/Models/Language.php';
require_once __DIR__ . '/../../../app/Models/Translation.php';

// Handle delete action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
    if ($userTypeModel->hasPermission($_SESSION['user_type_id'], 'languages_delete')) {
        $languageModel = new Language();
        $id = intval($_POST['id']);
        
        // Check if it's not the default language
        $language = $languageModel->findById($id);
        if ($language && !$language['is_default']) {
            if ($languageModel->delete($id)) {
                $_SESSION['message'] = 'Language deleted successfully';
                $_SESSION['message_type'] = 'success';
            } else {
                $_SESSION['message'] = 'Error deleting language';
                $_SESSION['message_type'] = 'danger';
            }
        } else {
            $_SESSION['message'] = 'Cannot delete default language';
            $_SESSION['message_type'] = 'danger';
        }
    }
    
    redirect('languages');
    exit;
}

$title = __('languages.title', 'Languages');
ob_start(); 
?>

<?php if (isset($_SESSION['message'])): ?>
    <div class="alert alert-<?php echo $_SESSION['message_type']; ?> alert-dismissible fade show" role="alert">
        <?php 
        echo $_SESSION['message']; 
        unset($_SESSION['message'], $_SESSION['message_type']);
        ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3 mb-0">
        <i class="fas fa-language"></i> <?= __('languages.management', 'Languages Management') ?>
    </h1>
    <div class="btn-group">
        <a href="/samanta_crm/languages/create" class="btn btn-primary">
            <i class="fas fa-plus"></i> <?= __('languages.add', 'Add Language') ?>
        </a>
    </div>
</div>

<div class="card">
    <div class="card-header py-2 d-flex justify-content-between align-items-center">
        <span class="small fw-bold"><i class="fas fa-table me-1"></i><?= __('languages.languages', 'Languages') ?></span>
    </div>
    <div class="card-body pt-0">
        <?php if (empty($languages)): ?>
            <div class="text-center py-5">
                <i class="fas fa-language fa-3x text-muted mb-3"></i>
                <h5><?= __('languages.no_languages', 'No languages found') ?></h5>
                <p class="text-muted"><?= __('languages.get_started', 'Get started by adding your first language.') ?></p>
                <a href="/samanta_crm/languages/create" class="btn btn-primary">
                    <i class="fas fa-plus"></i> <?= __('languages.add', 'Add Language') ?>
                </a>
            </div>
        <?php else: ?>
            <table class="table table-sm table-hover align-middle data-table mb-0" id="languagesTable">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th><?= __('languages.code', 'Code') ?></th>
                        <th><?= __('common.name', 'Name') ?></th>
                        <th><?= __('languages.native_name', 'Native Name') ?></th>
                        <th><?= __('languages.flag', 'Flag') ?></th>
                        <th><?= __('common.status', 'Status') ?></th>
                        <th><?= __('languages.default', 'Default') ?></th>
                        <th><?= __('common.created', 'Created') ?></th>
                        <th class="text-end"><?= __('common.actions', 'Actions') ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($languages as $language): ?>
                    <tr>
                        <td><?= $language['id'] ?></td>
                        <td>
                            <code><?= htmlspecialchars($language['code']) ?></code>
                        </td>
                        <td><strong><?= htmlspecialchars($language['name']) ?></strong></td>
                        <td><?= htmlspecialchars($language['native_name']) ?: '-' ?></td>
                        <td>
                            <?php if ($language['flag']): ?>
                                <span style="font-size: 1.2em;"><?= htmlspecialchars($language['flag']) ?></span>
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($language['is_active']): ?>
                                <span class="badge bg-success"><?= __('common.active', 'Active') ?></span>
                            <?php else: ?>
                                <span class="badge bg-secondary"><?= __('common.inactive', 'Inactive') ?></span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($language['is_default']): ?>
                                <span class="badge bg-primary"><?= __('languages.default', 'Default') ?></span>
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </td>
                        <td><?= date('M j, Y', strtotime($language['created_at'])) ?></td>
                        <td class="text-end">
                            <div class="btn-group btn-group-sm" role="group">
                                <a href="/samanta_crm/languages/<?= $language['id'] ?>/edit" class="btn btn-outline-primary" title="<?= __('common.edit', 'Edit') ?>">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <a href="/samanta_crm/languages/<?= $language['id'] ?>/translations" class="btn btn-outline-info" title="<?= __('languages.translations', 'Translations') ?>">
                                    <i class="fas fa-language"></i>
                                </a>
                                <button type="button" class="btn btn-outline-danger" onclick="deleteLanguage(<?= $language['id'] ?>, '<?= htmlspecialchars($language['name']) ?>')" title="<?= __('common.delete', 'Delete') ?>">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
    <?php if (!empty($languages)): ?>
    <div class="card-footer py-2 d-flex justify-content-between align-items-center">
        <span></span>
        <div class="small text-muted">
            <?= __('common.total', 'Total') ?>: <?= count($languages) ?> <?= __('common.items', 'items') ?>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Confirm Delete</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete language <strong id="deleteLanguageName"></strong>?</p>
                <p class="text-muted">This action cannot be undone and will fail if translations exist for this language.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?= __("common.cancel", "Cancel") ?></button>
                <form id="deleteForm" method="POST" style="display: inline;">
                    <button type="submit" class="btn btn-danger"><?= __("common.delete", "Delete") ?></button>
                </form>
            </div>
        </div>
    </div>
</div>

<?php 
$content = ob_get_clean();
$scripts = '
<script>
function deleteLanguage(id, name) {
    document.getElementById("deleteLanguageName").textContent = name;
    document.getElementById("deleteForm").action = "/samanta_crm/languages/" + id + "/delete";
    new bootstrap.Modal(document.getElementById("deleteModal")).show();
}
</script>
';
include '../app/Views/layout.php'; 
?>
      

