0) { $fish_data = fetchSingle("SELECT * FROM fish_types WHERE fish_id = ?", "i", [$fish_id]); if (!$fish_data) { $_SESSION['error'] = 'Fish type not found.'; header('Location: manage_fish_types.php'); exit(); } } // Handle form submission BEFORE any HTML output if ($_SERVER['REQUEST_METHOD'] === 'POST') { $csrf_token = $_POST['csrf_token'] ?? ''; if (!verifyCSRFToken($csrf_token)) { $error = 'Invalid request. Please try again.'; } else { $fish_name = sanitizeInput($_POST['fish_name'] ?? ''); $fish_name_tamil = sanitizeInput($_POST['fish_name_tamil'] ?? ''); $description = sanitizeInput($_POST['description'] ?? ''); $status = $_POST['status'] ?? 'active'; if (empty($fish_name)) { $error = 'Fish name is required.'; } elseif (!in_array($status, ['active', 'inactive'])) { $error = 'Invalid status selected.'; } else { if ($fish_id > 0) { // Update existing fish type $query = "UPDATE fish_types SET fish_name = ?, fish_name_tamil = ?, description = ?, status = ? WHERE fish_id = ?"; $stmt = executeQuery($query, "ssssi", [ $fish_name, $fish_name_tamil ?: null, $description ?: null, $status, $fish_id ]); if ($stmt) { logActivity($_SESSION['user_id'], 'Updated fish type', 'fish_types', $fish_id); $_SESSION['success'] = 'Fish type updated successfully!'; // Redirect BEFORE any output header('Location: manage_fish_types.php'); exit(); } else { $error = 'Failed to update fish type.'; } } else { // Create new fish type $query = "INSERT INTO fish_types (fish_name, fish_name_tamil, description, status, created_by) VALUES (?, ?, ?, ?, ?)"; $stmt = executeQuery($query, "ssssi", [ $fish_name, $fish_name_tamil ?: null, $description ?: null, $status, $_SESSION['user_id'] ]); if ($stmt) { $new_fish_id = getLastInsertId(); logActivity($_SESSION['user_id'], 'Created fish type', 'fish_types', $new_fish_id); $_SESSION['success'] = 'Fish type added successfully!'; // Redirect BEFORE any output header('Location: manage_fish_types.php'); exit(); } else { $error = 'Failed to add fish type.'; } } } } } // NOW include header (after all redirects are done) $page_title = ($fish_id > 0 ? 'Edit' : 'Add') . ' Fish Type'; require_once __DIR__ . '/../includes/header.php'; $csrf_token = generateCSRFToken(); ?>