<?php
/**
 * Gestión de divisiones y categorías - Backoffice administrativo
 * Turpial Airlines, C.A.
 */

$page_title = 'Gestión de Divisiones';

require_once '../includes/functions.php';
require_once '../includes/Division.php';

// Verificar autenticación y permisos
requirePermission(2); // Solo Admin y Super Admin

$division = new Division();
$category = new Category();

$action = $_GET['action'] ?? 'list';
$id = isset($_GET['id']) ? (int)$_GET['id'] : null;
$message = '';
$error = '';

// Procesar acciones POST
if ($_POST) {
    switch ($action) {
        case 'create_division':
        case 'edit_division':
            $data = [
                'name' => cleanString($_POST['name']),
                'description' => cleanString($_POST['description']),
                'manager' => cleanString($_POST['manager'])
            ];
            
            try {
                if ($action == 'create_division') {
                    $division->create($data);
                    $message = 'División creada exitosamente';
                } else {
                    $division->update($id, $data);
                    $message = 'División actualizada exitosamente';
                }
                $action = 'list';
            } catch (Exception $e) {
                $error = 'Error al procesar la división: ' . $e->getMessage();
            }
            break;
            
        case 'create_category':
        case 'edit_category':
            $data = [
                'division_id' => (int)$_POST['division_id'],
                'name' => cleanString($_POST['name']),
                'description' => cleanString($_POST['description'])
            ];
            
            try {
                if ($action == 'create_category') {
                    $category->create($data);
                    $message = 'Categoría creada exitosamente';
                } else {
                    $category->update($id, $data);
                    $message = 'Categoría actualizada exitosamente';
                }
                $action = 'list';
            } catch (Exception $e) {
                $error = 'Error al procesar la categoría: ' . $e->getMessage();
            }
            break;
    }
}

// Manejar acciones GET
if (isset($_GET['toggle_division']) && $id) {
    $division->toggleStatus($id);
    $message = 'Estado de la división actualizado';
    header('Location: divisions.php');
    exit;
}

if (isset($_GET['toggle_category']) && $id) {
    $category->toggleStatus($id);
    $message = 'Estado de la categoría actualizado';
    header('Location: divisions.php');
    exit;
}

// Obtener datos
$divisions = $division->getAll();
$categories = $category->getAll();

if (($action == 'edit_division' || $action == 'edit_category') && $id) {
    if (strpos($action, 'division') !== false) {
        $item = $division->getById($id);
    } else {
        $item = $category->getById($id);
    }
    
    if (!$item) {
        header('Location: divisions.php?error=not_found');
        exit;
    }
}

include 'includes/header.php';
?>

<?php if ($message): ?>
    <div class="alert alert-success alert-dismissible fade show">
        <i class="fas fa-check-circle me-2"></i><?php echo escape($message); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<?php if ($error): ?>
    <div class="alert alert-danger alert-dismissible fade show">
        <i class="fas fa-exclamation-triangle me-2"></i><?php echo escape($error); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<?php if ($action == 'list'): ?>
    <!-- Vista principal -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4><i class="fas fa-building me-2"></i>Divisiones y Categorías</h4>
        <div>
            <button type="button" class="btn btn-turpial me-2" data-bs-toggle="modal" data-bs-target="#createDivisionModal">
                <i class="fas fa-plus me-2"></i>Nueva División
            </button>
            <button type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#createCategoryModal">
                <i class="fas fa-plus me-2"></i>Nueva Categoría
            </button>
        </div>
    </div>
    
    <div class="row">
        <!-- Divisiones -->
        <div class="col-lg-6 mb-4">
            <div class="card">
                <div class="card-header bg-turpial-gradient">
                    <h5 class="mb-0"><i class="fas fa-building me-2"></i>Divisiones</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($divisions)): ?>
                        <div class="text-center py-4">
                            <i class="fas fa-building fa-3x text-muted mb-3"></i>
                            <p class="text-muted">No hay divisiones creadas</p>
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>Nombre</th>
                                        <th>Gerente</th>
                                        <th>Categorías</th>
                                        <th>Vacantes</th>
                                        <th>Estado</th>
                                        <th>Acciones</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($divisions as $div): ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo escape($div['name']); ?></strong><br>
                                                <small class="text-muted"><?php echo truncateText($div['description'], 50); ?></small>
                                            </td>
                                            <td><?php echo escape($div['manager']); ?></td>
                                            <td><span class="badge bg-info"><?php echo $div['categories_count']; ?></span></td>
                                            <td><span class="badge bg-success"><?php echo $div['vacancies_count']; ?></span></td>
                                            <td>
                                                <?php if ($div['is_active']): ?>
                                                    <span class="badge bg-success">Activa</span>
                                                <?php else: ?>
                                                    <span class="badge bg-secondary">Inactiva</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <div class="btn-group" role="group">
                                                    <a href="divisions.php?action=edit_division&id=<?php echo $div['id']; ?>" 
                                                       class="btn btn-sm btn-outline-warning" title="Editar">
                                                        <i class="fas fa-edit"></i>
                                                    </a>
                                                    <a href="divisions.php?toggle_division=1&id=<?php echo $div['id']; ?>" 
                                                       class="btn btn-sm btn-outline-info" title="Cambiar Estado">
                                                        <i class="fas fa-toggle-on"></i>
                                                    </a>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <!-- Categorías -->
        <div class="col-lg-6 mb-4">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-tags me-2"></i>Categorías</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($categories)): ?>
                        <div class="text-center py-4">
                            <i class="fas fa-tags fa-3x text-muted mb-3"></i>
                            <p class="text-muted">No hay categorías creadas</p>
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>Nombre</th>
                                        <th>División</th>
                                        <th>Vacantes</th>
                                        <th>Estado</th>
                                        <th>Acciones</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($categories as $cat): ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo escape($cat['name']); ?></strong><br>
                                                <small class="text-muted"><?php echo truncateText($cat['description'], 40); ?></small>
                                            </td>
                                            <td><?php echo escape($cat['division_name']); ?></td>
                                            <td><span class="badge bg-success"><?php echo $cat['vacancies_count']; ?></span></td>
                                            <td>
                                                <?php if ($cat['is_active']): ?>
                                                    <span class="badge bg-success">Activa</span>
                                                <?php else: ?>
                                                    <span class="badge bg-secondary">Inactiva</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <div class="btn-group" role="group">
                                                    <a href="divisions.php?action=edit_category&id=<?php echo $cat['id']; ?>" 
                                                       class="btn btn-sm btn-outline-warning" title="Editar">
                                                        <i class="fas fa-edit"></i>
                                                    </a>
                                                    <a href="divisions.php?toggle_category=1&id=<?php echo $cat['id']; ?>" 
                                                       class="btn btn-sm btn-outline-info" title="Cambiar Estado">
                                                        <i class="fas fa-toggle-on"></i>
                                                    </a>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Modal Crear División -->
    <div class="modal fade" id="createDivisionModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST" action="divisions.php?action=create_division">
                    <div class="modal-header">
                        <h5 class="modal-title">Nueva División</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="div_name" class="form-label">Nombre *</label>
                            <input type="text" class="form-control" id="div_name" name="name" required>
                        </div>
                        <div class="mb-3">
                            <label for="div_manager" class="form-label">Gerente</label>
                            <input type="text" class="form-control" id="div_manager" name="manager">
                        </div>
                        <div class="mb-3">
                            <label for="div_description" class="form-label">Descripción</label>
                            <textarea class="form-control" id="div_description" name="description" rows="3"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                        <button type="submit" class="btn btn-turpial">Crear División</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Modal Crear Categoría -->
    <div class="modal fade" id="createCategoryModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST" action="divisions.php?action=create_category">
                    <div class="modal-header">
                        <h5 class="modal-title">Nueva Categoría</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="cat_division" class="form-label">División *</label>
                            <select class="form-select" id="cat_division" name="division_id" required>
                                <option value="">Seleccionar...</option>
                                <?php foreach ($divisions as $div): ?>
                                    <?php if ($div['is_active']): ?>
                                        <option value="<?php echo $div['id']; ?>"><?php echo escape($div['name']); ?></option>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="cat_name" class="form-label">Nombre *</label>
                            <input type="text" class="form-control" id="cat_name" name="name" required>
                        </div>
                        <div class="mb-3">
                            <label for="cat_description" class="form-label">Descripción</label>
                            <textarea class="form-control" id="cat_description" name="description" rows="3"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                        <button type="submit" class="btn btn-primary">Crear Categoría</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

<?php elseif ($action == 'edit_division'): ?>
    <!-- Editar división -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4><i class="fas fa-edit me-2"></i>Editar División</h4>
        <a href="divisions.php" class="btn btn-outline-secondary">
            <i class="fas fa-arrow-left me-2"></i>Volver
        </a>
    </div>
    
    <div class="row justify-content-center">
        <div class="col-lg-6">
            <div class="card">
                <div class="card-body">
                    <form method="POST">
                        <div class="mb-3">
                            <label for="name" class="form-label">Nombre *</label>
                            <input type="text" class="form-control" id="name" name="name" 
                                   value="<?php echo escape($item['name']); ?>" required>
                        </div>
                        <div class="mb-3">
                            <label for="manager" class="form-label">Gerente</label>
                            <input type="text" class="form-control" id="manager" name="manager" 
                                   value="<?php echo escape($item['manager']); ?>">
                        </div>
                        <div class="mb-3">
                            <label for="description" class="form-label">Descripción</label>
                            <textarea class="form-control" id="description" name="description" rows="4"><?php echo escape($item['description']); ?></textarea>
                        </div>
                        
                        <div class="d-flex justify-content-between">
                            <a href="divisions.php" class="btn btn-outline-secondary">
                                <i class="fas fa-times me-2"></i>Cancelar
                            </a>
                            <button type="submit" class="btn btn-turpial">
                                <i class="fas fa-save me-2"></i>Actualizar
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

<?php elseif ($action == 'edit_category'): ?>
    <!-- Editar categoría -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4><i class="fas fa-edit me-2"></i>Editar Categoría</h4>
        <a href="divisions.php" class="btn btn-outline-secondary">
            <i class="fas fa-arrow-left me-2"></i>Volver
        </a>
    </div>
    
    <div class="row justify-content-center">
        <div class="col-lg-6">
            <div class="card">
                <div class="card-body">
                    <form method="POST">
                        <div class="mb-3">
                            <label for="division_id" class="form-label">División *</label>
                            <select class="form-select" id="division_id" name="division_id" required>
                                <?php foreach ($divisions as $div): ?>
                                    <option value="<?php echo $div['id']; ?>" 
                                            <?php echo $item['division_id'] == $div['id'] ? 'selected' : ''; ?>>
                                        <?php echo escape($div['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="name" class="form-label">Nombre *</label>
                            <input type="text" class="form-control" id="name" name="name" 
                                   value="<?php echo escape($item['name']); ?>" required>
                        </div>
                        <div class="mb-3">
                            <label for="description" class="form-label">Descripción</label>
                            <textarea class="form-control" id="description" name="description" rows="4"><?php echo escape($item['description']); ?></textarea>
                        </div>
                        
                        <div class="d-flex justify-content-between">
                            <a href="divisions.php" class="btn btn-outline-secondary">
                                <i class="fas fa-times me-2"></i>Cancelar
                            </a>
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save me-2"></i>Actualizar
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

<?php endif; ?>

<?php include 'includes/footer.php'; ?>