<?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';
        }
    }
    
    header('Location: /samanta_crm/languages');
    exit;
}

$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 m
        <i class="fas fa-globe"></i> Languages Management
    </h1>
    <a href="/samanta_crm/languages/create" class="btn btn-primary">
        <i class="fas fa-plus"></i> Add Language
    </a>
</div>

<div class="card">
    <div class="card-body">
        <?php if (empty($languages)): ?>
            <div class="text-center py-4">
                <i class="fas fa-globe fa-3x text-muted mb-3"></i>
                <h5>No languages found</h5>
                <p class="text-muted">Get started by adding your first language.</p>
                <a href="/samanta_crm/languages/create" class="btn btn-primary">
                    <i class="fas fa-plus"></i> Add Language
                </a>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover" id="languagesTable">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Code</th>
                            <th><?= __("common.name", "Name") ?></th>
                            <th>Native Name</th>
                            <th>Flag</th>
                            <th><?= __("common.status", "Status") ?></th>
                            <th>Default</th>
                            <th>Created</th>
                            <th><?= __("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><?= htmlspecialchars($language['name']) ?></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">Default</span>
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </td>
                            <td><?= date('M j, Y', strtotime($language['created_at'])) ?></td>
                            <td>
                                <div class="btn-group btn-group-sm" role="group">
                                    <a href="/samanta_crm/languages/<?= $language['id'] ?>/edit" class="btn btn-outline-primary">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="/samanta_crm/languages/<?= $language['id'] ?>/translations" class="btn btn-outline-info">
                                        <i class="fas fa-language"></i>
                                    </a>
                                    <button type="button" class="btn btn-outline-danger" onclick="deleteLanguage(<?= $language['id'] ?>, '<?= htmlspecialchars($language['name']) ?>')">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</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'; 
?>
      