<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/admin_layout.php';

library_bootstrap();

$errors = [];

// Handle POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;

    try {
        if ($action === 'create_type') {
            $nameEn = trim($_POST['name_en'] ?? '');
            $nameAr = trim($_POST['name_ar'] ?? '');
            if (!$nameEn || !$nameAr) {
                throw new RuntimeException('Both English and Arabic names are required for Type.');
            }
            library_create_type($nameEn, $nameAr);
            library_set_flash('success', 'Type created successfully.');
            header('Location: /admin_types.php');
            exit;
        } elseif ($action === 'update_type') {
            $nameEn = trim($_POST['name_en'] ?? '');
            $nameAr = trim($_POST['name_ar'] ?? '');
            if (!$id || !$nameEn || !$nameAr) {
                throw new RuntimeException('ID, English name, and Arabic name are required.');
            }
            library_update_type($id, $nameEn, $nameAr);
            library_set_flash('success', 'Type updated successfully.');
            header('Location: /admin_types.php');
            exit;
        } elseif ($action === 'delete_type') {
            if (!$id) {
                throw new RuntimeException('Invalid Type ID.');
            }
            library_delete_type($id);
            library_set_flash('success', 'Type deleted successfully.');
            header('Location: /admin_types.php');
            exit;
        }
    } catch (Throwable $exception) {
        $errors[] = $exception->getMessage();
    }
}

// Search Logic
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$types = library_get_types($search);

admin_render_header('Document Types', 'types');
?>
<!-- Page Content -->
<?php if ($errors): ?>
    <div class="alert alert-danger"><?= h(implode(' ', $errors)) ?></div>
<?php endif; ?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <p class="text-secondary mb-0">Manage document types (e.g., Document, Film, etc.).</p>
    <button class="btn btn-primary" onclick="openCreateTypeModal()">
        <i class="bi bi-plus-lg me-1"></i> Add New Type
    </button>
</div>

<!-- Search Bar -->
<div class="card shadow-sm border-0 mb-4">
    <div class="card-body">
        <form method="get" action="/admin_types.php" class="row g-2 align-items-center">
            <div class="col-auto flex-grow-1">
                <input type="text" name="search" class="form-control" placeholder="Search types..." value="<?= h($search) ?>">
            </div>
            <div class="col-auto">
                <button type="submit" class="btn btn-outline-primary">
                    <i class="bi bi-search"></i> Search
                </button>
                <?php if ($search): ?>
                    <a href="/admin_types.php" class="btn btn-outline-secondary">Clear</a>
                <?php endif; ?>
            </div>
        </form>
    </div>
</div>

<div class="card shadow-sm border-0">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th class="ps-4">Name</th>
                        <th class="text-end pe-4">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($types)): ?>
                        <tr><td colspan="2" class="text-center py-5 text-muted">No types found.</td></tr>
                    <?php else: ?>
                        <?php foreach ($types as $type): ?>
                            <tr>
                                <td class="ps-4">
                                    <div class="fw-medium text-dark"><?= h($type['name_en']) ?></div>
                                    <small class="text-muted"><?= h($type['name_ar']) ?></small>
                                </td>
                                <td class="text-end pe-4">
                                    <button class="btn btn-sm btn-outline-secondary me-1" 
                                            data-id="<?= $type['id'] ?>"
                                            data-name-en="<?= h($type['name_en']) ?>"
                                            data-name-ar="<?= h($type['name_ar']) ?>"
                                            onclick="openEditTypeModal(this)">
                                        <i class="bi bi-pencil"></i> Edit
                                    </button>
                                    <button class="btn btn-sm btn-outline-danger" onclick="deleteType(<?= $type['id'] ?>)">
                                        <i class="bi bi-trash"></i> Delete
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Type Modal -->
<div class="modal fade" id="typeModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <form method="post" action="/admin_types.php" id="typeForm">
        <input type="hidden" name="action" id="type_action" value="create_type">
        <input type="hidden" name="id" id="type_id" value="">
        <div class="modal-header">
            <h5 class="modal-title" id="typeModalTitle">Add New Type</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
            <div class="mb-3">
                <label class="form-label">Name (English)</label>
                <div class="input-group">
                    <input type="text" class="form-control" name="name_en" id="type_name_en" required>
                    <button class="btn btn-outline-secondary" type="button" onclick="translateText('type_name_en', 'type_name_ar', 'Arabic')" title="Translate to Arabic">
                        <i class="bi bi-translate"></i>
                    </button>
                </div>
            </div>
            <div class="mb-3">
                <label class="form-label">Name (Arabic)</label>
                <div class="input-group">
                    <input type="text" class="form-control" name="name_ar" id="type_name_ar" dir="rtl" required>
                    <button class="btn btn-outline-secondary" type="button" onclick="translateText('type_name_ar', 'type_name_en', 'English')" title="Translate to English">
                        <i class="bi bi-translate"></i>
                    </button>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            <button type="submit" class="btn btn-primary">Save</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Delete Confirmation Form -->
<form method="post" action="/admin_types.php" id="deleteForm">
    <input type="hidden" name="action" id="deleteAction" value="">
    <input type="hidden" name="id" id="deleteId" value="">
</form>

<script>
    let typeModal;

    document.addEventListener('DOMContentLoaded', function() {
        typeModal = new bootstrap.Modal(document.getElementById('typeModal'));
    });

    function openCreateTypeModal() {
        document.getElementById('typeModalTitle').innerText = 'Add New Type';
        document.getElementById('type_action').value = 'create_type';
        document.getElementById('type_id').value = '';
        document.getElementById('type_name_en').value = '';
        document.getElementById('type_name_ar').value = '';
        typeModal.show();
    }

    function openEditTypeModal(btn) {
        const id = btn.getAttribute('data-id');
        const nameEn = btn.getAttribute('data-name-en');
        const nameAr = btn.getAttribute('data-name-ar');

        document.getElementById('typeModalTitle').innerText = 'Edit Type';
        document.getElementById('type_action').value = 'update_type';
        document.getElementById('type_id').value = id;
        document.getElementById('type_name_en').value = nameEn;
        document.getElementById('type_name_ar').value = nameAr;
        typeModal.show();
    }

    function deleteType(id) {
        if (confirm('Are you sure you want to delete this type?')) {
            document.getElementById('deleteAction').value = 'delete_type';
            document.getElementById('deleteId').value = id;
            document.getElementById('deleteForm').submit();
        }
    }
</script>

<?php admin_render_footer(); ?>